在 C# 中定义新的运算符?
可能的重复:
是否可以在 C# 中创建新运算符?< /a>
我喜欢 C#,但我希望它能够在类上定义我自己的运算符,例如 A => B 而不必执行 A.Implies(B)。我认为如果您可以将 [+-*/&^|%$#@><]+ 等集合中任意长度的标识符分配给类方法,然后像运算符一样使用它,那就太酷了。有谁知道是否有某种扩展,或者甚至有可能进行扩展,这样做吗?
Possible Duplicate:
Is it possible to create a new operator in c#?
I love C#, but one thing I wish it had was the ability to define my own operators on classes, like A => B instead of having to do A.Implies(B). I think it would be really cool if you could assign an identifier of any length in a set like [+-*/&^|%$#@><]+ to a class method and then use it like an operator. Does anybody know if there's some sort of extension, or if it's even possible to make one, that does this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这不是语言中内置的。您必须重载该语言附带的预定义运算符(可重载运算符)。
如果您喜欢这种调试方式,您可能需要考虑 F#。它是一种运行在 .NET 框架之上的函数式语言,使您能够定义所需的任何运算符。
This is not built into the language. You are stuck with overloading the predefined operators that come with the language (overloadable operators).
If you like that style of debugging you might want to consider F#. It is a functional language that runs on top the .NET framework and gives you the ability to define any operator you want.
可以重载的运算符列表位于此处。
运算符重载只能让您更改运算符的行为,而不能定义新的运算符。
尽管
A => B
作为A.Implies(B)
可能听起来很酷,但它会在以后给你带来问题(6 个月后,当你试图弄清楚你的代码应该做什么时) 。The list of operators that can be overloaded is here.
Operator overloading only lets you change the behavior of operators, not define new ones.
And although
A => B
asA.Implies(B)
might sound cool, it will cause you problems later (in 6 months, when you're trying to figure out what your code is supposed to do).简而言之,不。你将不得不看看另一种语言。您可以重载许多现有运算符,或定义任何其他方法(包括非常方便的扩展方法) - 但您不能在任何变体中定义自定义运算符我所知道的C#。
In short, no. You would have to look at another language. You can overload many of the existing operators, or define any other methods (including extension methods which are very handy) - but you can't define custom operators in any variant of C# that I know of.
不,这是不可能的,除非您制作自己的类似 C# 的编译器。
您只能重写一些内置运算符,不能创建新运算符,并且无法重写 lambda 运算符 (=>)。
No, this is not possible, unless you make your own C#-like compiler.
You can only override some of the built-in operators, you can not create new ones, and the lambda operator (=>) cannot be overridden.