运算符重载用C#扩展方法 [英] Operator Overloading with C# Extension Methods

查看:150
本文介绍了运算符重载用C#扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用扩展方法来一个算超载添加到C#的StringBuilder 类。具体而言,由于的StringBuilder SB ,我想 SB + =文本成为等同于 sb.Append(文本)

I'm attempting to use extension methods to add an operater overload to the C# StringBuilder class. Specifically, given StringBuilder sb, I'd like sb += "text" to become equivalent to sb.Append("text").

下面是创建一个扩展方法的语法的StringBuilder

Here's the syntax for creating an extension method for StringBuilder:

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

它成功地增加了等等扩展方法到的StringBuilder

不幸的是,运算符重载似乎并没有工作:

Unfortunately, operator overloading does not seem to work:

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

在其他问题上,关键字这个在这种情况下是不允许的。

Among other issues, the keyword this is not allowed in this context.

通过扩展方法添加运算符重载可能吗?如果是这样,什么是去了解它的正确方法?

Are adding operator overloads via extension methods possible? If so, what's the proper way to go about it?

推荐答案

这是目前不可能,因为扩展方法必须是静态类和静态类不能有操作符重载。

This is not currently possible, because extension methods must be in static classes, and static classes can't have operator overloads.

的Mads托格森,C#语言PM说:

Mads Torgersen, C# Language PM says:

...为Orcas的版本中,我们决定
  采取谨慎的态度,并添加
  唯一的规则扩展方法,如
  反对延伸性能,
  事件,操作员,静态方法等
  等常规扩展方法是
  我们需要什么样的LINQ,他们有
  在语法上最小的设计,
  不能被轻易模仿一些
  其他成员种。

...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!

编辑:

我只注意到,的Mads在同一篇文章中写道更多:

I just noticed, Mads wrote more in the same article:

我很遗憾地宣布,我们不会
  在未来的版本中这样做。我们
  并采取延长成员非常
  认真地在我们的计划,并花了
  很多努力试图让他们
  没错,但最终我们无法得到
  它不够光滑,并决定给
  方式到其他有趣的功能。

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#扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆