使用 C# 扩展方法的运算符重载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/172658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Operator Overloading with C# Extension Methods
提问by Jude Allred
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")
.
我正在尝试使用扩展方法向 C#StringBuilder
类添加操作员重载。具体来说,鉴于StringBuilder
sb
,我想sb += "text"
变得等同于sb.Append("text")
。
Here's the syntax for creating an extension method for StringBuilder
:
下面是创建扩展方法的语法StringBuilder
:
public static class sbExtensions
{
public static StringBuilder blah(this StringBuilder sb)
{
return sb;
}
}
It successfully adds the blah
extension method to the StringBuilder
.
它成功地将blah
扩展方法添加到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.
除其他问题外,this
在此上下文中不允许使用关键字。
Are adding operator overloads via extension methods possible? If so, what's the proper way to go about it?
是否可以通过扩展方法添加运算符重载?如果是这样,正确的方法是什么?
采纳答案by Jacob Krall
This is not currently possible, because extension methods must be in static classes, and static classes can't have operator overloads.
这目前是不可能的,因为扩展方法必须在静态类中,而静态类不能有运算符重载。
Mads Torgersen, C# Language PM says:
Mads Torgersen,C# 语言 PM 说:
...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!
...对于 Orcas 版本,我们决定采取谨慎的方法,只添加常规扩展方法,而不是扩展属性、事件、运算符、静态方法等。常规扩展方法是我们 LINQ 所需要的,并且它们具有一种语法上最小的设计,对于其他一些成员类型无法轻易模仿。
我们越来越意识到其他类型的扩展成员可能有用,因此我们将在 Orcas 之后回到这个问题。但是没有保证!
Edit:
编辑:
I just noticed, Mads wrote more in the same article:
我刚刚注意到,Mads 在同一篇文章中写了更多:
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.
我很遗憾地报告,我们将不会在下一个版本中这样做。我们确实在我们的计划中非常重视扩展成员,并花了很多精力试图让他们正确,但最终我们无法让它足够顺利,并决定让位于其他有趣的功能。
这仍然在我们未来版本的雷达上。如果我们获得大量引人注目的场景来帮助推动正确的设计,那么将会有所帮助。
This feature is currently on the table (potentially) for C# 8.0.Mads talks a bit more about implementing it here.
此功能目前(可能)在 C# 8.0 中可用。Mads在此处详细介绍了如何实现它。
回答by Dylan Beattie
It appears this isn't currently possible - there's an open feedback issue requesting this very feature on Microsoft Connect:
目前看来这是不可能的 - 有一个开放的反馈问题要求在 Microsoft Connect 上使用此功能:
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=168224
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=168224
suggesting it might appear in a future release but isn't implemented for the current version.
暗示它可能会出现在未来的版本中,但未在当前版本中实现。
回答by Jord?o
If you control the places where you want to use this "extension operator" (which you normally do with extension methods anyway), you can do something like this:
如果您控制要使用此“扩展运算符”的位置(无论如何您通常都会使用扩展方法),您可以执行以下操作:
class Program {
static void Main(string[] args) {
StringBuilder sb = new StringBuilder();
ReceiveImportantMessage(sb);
Console.WriteLine(sb.ToString());
}
// the important thing is to use StringBuilderWrapper!
private static void ReceiveImportantMessage(StringBuilderWrapper sb) {
sb += "Hello World!";
}
}
public class StringBuilderWrapper {
public StringBuilderWrapper(StringBuilder sb) { StringBuilder = sb; }
public StringBuilder StringBuilder { get; private set; }
public static implicit operator StringBuilderWrapper(StringBuilder sb) {
return new StringBuilderWrapper(sb);
}
public static StringBuilderWrapper operator +(StringBuilderWrapper sbw, string s) {
sbw.StringBuilder.Append(s);
return sbw;
}
}
The StringBuilderWrapper
class declares an implicit conversion operatorfrom a StringBuilder
anddeclares the desired +
operator. This way, a StringBuilder
can be passed to ReceiveImportantMessage
, which will be silently converted to a StringBuilderWrapper
, where the +
operator can be used.
的StringBuilderWrapper
类声明的隐式转换运算符从一个StringBuilder
和声明所需的+
算子。这样, aStringBuilder
可以传递给ReceiveImportantMessage
,它将被静默转换为 a StringBuilderWrapper
,在那里+
可以使用运算符。
To make this fact more transparent to callers, you can declare ReceiveImportantMessage
as taking a StringBuilder
and just use code like this:
为了使这个事实对调用者更透明,您可以声明ReceiveImportantMessage
为采用 aStringBuilder
并使用如下代码:
private static void ReceiveImportantMessage(StringBuilder sb) {
StringBuilderWrapper sbw = sb;
sbw += "Hello World!";
}
Or, to use it inline where you're already using a StringBuilder
, you can simply do this:
或者,要在您已经使用 a 的地方使用它StringBuilder
,您可以简单地执行以下操作:
StringBuilder sb = new StringBuilder();
StringBuilderWrapper sbw = sb;
sbw += "Hello World!";
Console.WriteLine(sb.ToString());
I created a postabout using a similar approach to make IComparable
more understandable.
回答by Chuck Rostance
Though it's not possible to do the operators, you could always just create Add (or Concat), Subtract, and Compare methods....
尽管不可能使用运算符,但您始终可以创建 Add(或 Concat)、Subtract 和 Compare 方法....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Whatever.Test
{
public static class Extensions
{
public static int Compare(this MyObject t1, MyObject t2)
{
if(t1.SomeValueField < t2.SomeValueField )
return -1;
else if (t1.SomeValueField > t2.SomeValueField )
{
return 1;
}
else
{
return 0;
}
}
public static MyObject Add(this MyObject t1, MyObject t2)
{
var newObject = new MyObject();
//do something
return newObject;
}
public static MyObject Subtract(this MyObject t1, MyObject t2)
{
var newObject= new MyObject();
//do something
return newObject;
}
}
}
回答by david van brink
Hah! I was looking up "extension operator overloading" with exactly the same desire, for sb += (thing).
哈!对于 sb += (thing),我正在以完全相同的愿望查找“扩展运算符重载”。
After reading the answers here (and seeing that the answer is "no"), for my particular needs, I went with an extension method which combines sb.AppendLine and sb.AppendFormat, and looks tidier than either.
在阅读了这里的答案(并且看到答案是“否”)之后,对于我的特殊需求,我使用了一个结合了 sb.AppendLine 和 sb.AppendFormat 的扩展方法,并且看起来比任何一个都更整洁。
public static class SomeExtensions
{
public static void Line(this StringBuilder sb, string format, params object[] args)
{
string s = String.Format(format + "\n", args);
sb.Append(s);
}
}
And so,
所以,
sb.Line("the first thing is {0}",first);
sb.Line("the second thing is {0}", second);
Not a general answer, but may be of interest to future seekers looking at this kind of thing.
不是一般的答案,但可能对未来寻找这种事情的寻求者感兴趣。
回答by will motil
Its possible to rigg it with a wrapper and extensions but impossible to do it properly. You end with garbage which totally defeats the purpose. I have a post up somewhere on here that does it, but its worthless.
可以用包装器和扩展件来装配它,但不可能正确地做到这一点。你以完全违背目的的垃圾结束。我在这里的某个地方有一个帖子可以做到这一点,但它毫无价值。
Btw All numeric conversions create garbage in string builder that needs to be fixed. I had to write a wrapper for that which does work and i use it. That is worth perusing.
顺便说一句,所有数字转换都会在需要修复的字符串生成器中产生垃圾。我不得不为那个工作的东西写一个包装器,我使用它。那值得细读。