在 C# 中定义新的运算符?

发布于 2024-08-22 11:39:30 字数 474 浏览 7 评论 0原文

可能的重复:
是否可以在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小巷里的女流氓 2024-08-29 11:39:30

这不是语言中内置的。您必须重载该语言附带的预定义运算符(可重载运算符)。

如果您喜欢这种调试方式,您可能需要考虑 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.

贩梦商人 2024-08-29 11:39:30

可以重载的运算符列表位于此处

运算符重载只能让您更改运算符的行为,而不能定义新的运算符。

尽管 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 as A.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).

叫思念不要吵 2024-08-29 11:39:30

简而言之,不。你将不得不看看另一种语言。您可以重载许多现有运算符,或定义任何其他方法(包括非常方便的扩展方法) - 但您不能在任何变体中定义自定义运算符我所知道的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.

森罗 2024-08-29 11:39:30

不,这是不可能的,除非您制作自己的类似 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文