c# - 使用 C# 扩展方法重载运算符

标签 c# extension-methods operator-overloading

我正在尝试使用扩展方法将运算符重载添加到 C# StringBuilder 类。具体来说,给定 StringBuilder sb,我希望 sb += "text" 等效于 sb.Append("text ").

下面是为 StringBuilder 创建扩展方法的语法:

public static class sbExtensions
{
    public static StringBuilder blah(this StringBuilder sb)
    {
        return sb;
    }
} 

它成功地将 blah 扩展方法添加到 StringBuilder

不幸的是,运算符重载似乎不起作用:

public static class sbExtensions
{
    public static StringBuilder operator +(this StringBuilder sb, string s)
    {
        return sb.Append(s);
    }
} 

除其他问题外,此上下文中不允许使用关键字 this

是否可以通过扩展方法添加运算符重载?如果是这样,正确的做法是什么?

最佳答案

目前这是不可能的,因为扩展方法必须在静态类中,而静态类不能有运算符重载。但是 feature is being discussed for some future release of C# . Mads 谈了更多关于实现它的内容 in this video from 2017 .

C# 语言项目经理 Mads Torgersen 在谈到目前尚未实现的原因时说:

...for the Orcas release we decided to take the cautious approach and add only regular extension methods, as opposed to extention properties, events, operators, static methods, etc etc. Regular extension methods were what we needed for LINQ, and they had a syntactically minimal design that could not be easily mimicked for some of the other member kinds.

We are becoming increasingly aware that other kinds of extension members could be useful, and so we will return to this issue after Orcas. No guarantees, though!

在同一篇文章的下方:

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.

关于c# - 使用 C# 扩展方法重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/172658/

相关文章:

c# - 扩展方法和编译时检查

c# - Lambda表达式(扩展函数Select是怎么定义的?)

c# - 如何判断扩展方法是否影响 'this'?

c++ - 为什么 cout 在重载运算符 << 的友元函数中不起作用,它是一个 istream 运算符

c++ - 不工作 : override the default less-than operator of shared_ptr of a class

c# - 如何为 .Net 构建 PDFBox

c# - 使用 Caliburn.Micro 设置窗口标题

c# - 没有为一个或多个必需参数提供值 ERROR

c# - 400 错误请求 - 在本地进行 nancy 自托管 Web API 调用时主机名无效

c++ - 类型之间的转换