重新设计允许可变性的扩展方法(对于引用类型)

Redesigning extension method allowing for mutability (for reference types)

我一直使用不可变的扩展方法,并为它们执行的任何对象生成一个新的和改进的版本。

public static ReferenceType Biggify(this ReferenceType self)
{
  return self.Something();
}

现在我意识到使用这样的扩展方法对 self 而不是 return jack 做一些事情可能会很好。

public static void Biggify(this ReferenceType self)
{
  self = self.SomethingElse();
}

但是,我意识到上面的操作只会在 self 的副本上执行,并且当我们退出方法的范围时,变异将被丢弃。

  1. 我可以完全启用扩展方法的可变性吗?

如果是的话...

  1. 我该怎么做
  2. 我应该那样做吗?

没有

扩展方法的第一个 (this) 参数不能是 ref,因此您不能修改对传入对象的引用。

确实,如果对象本身是可变扩展,则可以轻松地显式更改对象:

  void AddCouple<T>(this List<T> list) where T:new()
  {
      list.Add(new T());
      list.Add(new T());
  }

或无意间点赞:

   List<T> AddToCopy<T>(this List<T> list, T newItem)
   {
       var newList = list;
       newList.Add(newItem); // changed existing list...
       return newList;
   }

Doesn't C# Extension Methods allow passing parameters by reference? 中有一些额外的讨论,特别是关于不可变 types/value 类型的扩展。