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

本文关键字:方法 引用类型 扩展 可变性 许可 | 更新日期: 2023-09-27 18:03:29

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

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

现在我意识到有这样一个扩展方法对self做一些事情,而不返回jack,就像这样。

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

然而,我意识到上述操作将只在self的副本上执行,并且当我们退出该方法的作用域时,突变将被丢弃。

  1. 我可以为扩展方法启用可变性吗?

如果是…

  • 我怎么做?
  • 我应该这样做吗?
  • 重新设计允许可变性的扩展方法(对于引用类型)

    No.

    扩展方法的第一个(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;
       }
    

    c#扩展方法是否允许通过引用传递参数?