扩展运算符重载未来的可能性吗?

Is Extended Operator Overloading A Future Possibility?

我最近得到了 Joseph 和 Ben Albahari 的 C# 7.0 in a Nutshell 的副本。当我浏览关于高级 C# 的章节时,特别是第 199 页,它开始介绍运算符重载;我开始怀疑,是否有任何关于运算符重载的官方说法,类似于至少原始类型的扩展方法?例如:

// Traditional Overload
public static MyType operator +(MyType, MyType);

// Traditional Extension Method
public static int Sum(this int, int[]);

// Possible Combination?
public static int operator +(this int, int, string);

在上面的例子中,有加法运算符的传统重载;这允许我执行自定义添加我的类型的属性以提供新值。然后是传统的扩展方法,我们可以通过添加我们认为有用的方法来扩展类型;与上面的示例类似,如果我经常对整数数组中的所有值执行加法运算以获得它们的总和,那么我可以创建一个有用的扩展方法来实现:

int sum = int.Sum(myArrayOfIntegers);

综上所述,扩展运算符重载可能很有用,至少对于原语而言是这样。例如:

public static int operator +(this int i, int x, string y) {
    // Perform parsing of the string and return the newly added value between x and y.
}

然后我可以在有用的地方对多个原始类型执行算术运算,而不必不断地尝试解析我的代码中的数据。并不是说解析数据很难,而是当你不得不做数百次同样的事情(包括调用一个方法来执行解析和算术)时,它会变得很乏味。

自从 2008 年回答 this post 以来,我进行了一些搜索,但找不到与此主题相关的任何内容。十年是很长的时间,我希望 [=29] 的意见=] 从那以后发生了变化。

I am sorry to report that we will not be doing this in the next release. We did take extension members very seriously in our plans, and spent a lot of effort trying to get them right, but in the end we couldn't get it smooth enough, and decided to give way to other interesting features.

This is still on our radar for future releases. What will help is if we get a good amount of compelling scenarios that can help drive the right design.

在我看来,仍然在我们的雷达上并不是很有希望。

请仅在资源可信且最新(或在过去 2 年内)的情况下提供答案。

是的。在 C# 8 中,可能会有“Extension Everything”,如 Github 上解释的那样 here

“Extension Everything”包括什么:

  • 扩展静态字段
  • 扩展静态方法
  • 扩展静态属性
  • 扩展属性
  • 扩展索引器
  • 扩展投射
  • 扩展运营商

不包括的内容:

  • 扩展实例字段(最初)
  • 扩展构造函数(最初)
  • 扩展事件(最初)
  • 扩展自动属性(直到它们支持扩展实例字段)

语法可能是这样的:

public extension class List2DExt<T> : List<List<T>> 
{
    // Extension static field
    private static int _flattenCount = 0;

    // Extension static property
    public static int FlattenCount => _flattenCount;

    // Extension static method
    public static int Get FlattenCount() => _flattenCount;

    // New syntax for extension methods
    public List<T> Flatten() { ... }

    // Extension indexers
    public List<List<T>> this[int[] indices] => ...;

    // Extension implicit operator
    public static implicit operator List<T>(List<List<T>> self) => self.Flatten();

    // Extension operator overload
    public static implicit List<List<T>> operator +(List<List<T>> left, List<List<T>> right) => left.Concat(right);
}

起初不支持实例字段的原因是他们必须如何跟踪这些字段的状态,我想这很棘手。