OR(|)、XOR(^)、AND(&) 重载
如何重载 &, | C# 中的 和 ^ 运算符以及重载如何工作?
一段时间以来我一直在尝试寻找一些好的答案,但还没有找到。我将分享任何有用的文章。
How do I overload the &, | and ^ operators in C# and how does overloading work?
I have been trying to find some good answers for some time but have not found any. I will share any helpful articles.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有关运算符重载(包括二进制/按位运算符)和示例源代码的一些文章/教程/参考,请参阅:
至于“如何使用它们”,基本规则是重载运算符应该在您实现它们的领域中有意义...
例如,您可以构建遗传/进化算法并以与该算法的“重组/突变”步骤(即从当前群体创建下一代)-这将在该特定上下文中生成相当优雅的代码。
For some articles/tutorials/references on operator overloading including binary/bitwise operators and sample source code see:
As for "how to use them" the basic rule is that overloaded operators should make sense in the domain you implement them...
For example you could build a genetic/evolutionary algorithm and define some/all of the bitwise/binary operators in a way consistent with the "recombination/mutation" step (i.e. creating the next generation from current population) of that algorithm - this would make for rather elegant code in that specific context.
通过在 C# 中为类实现运算符,您实际上并没有重载运算符。您只是第一次实施它们。它们是方法,就像任何其他方法一样,但具有特殊的语法。您不调用
c = Add(a, b)
,而是调用c = a + b
,其中+
是返回的运算符(方法)一个值。通过实现以下方法,已经自动实现了
&=
、|=
和^=
方法。重载在编译时执行。它确保根据方法的名称、参数类型和计数来调用特定的方法。
覆盖在运行时执行。它允许调用子类的方法而不是父类的方法,即使实例被视为父类也是如此。
By implementing operators for your classes in C#, you are not actually overloading operators. You are simply implementing them for the first time. They are methods, just like any other, but with special syntax. Instead of calling
c = Add(a, b)
you callc = a + b
, where+
is an operator (method) that returns a value.By implementing the following methods, the
&=
|=
, and^=
methods have been automatically implemented.Overloading is performed at compile time. It ensures that a specific method is called based on the method's name and parameter type and count.
Overiding is performed at runtime. It allows a subclass's method to be called instead of the parent method, even when the instance was being treated as the parent class.
如何使用它们?小心。
他们需要讲道理。
例如,定义一个类型来保存 ComplexNumber 或 Matrix,然后重载算术运算符是有意义的。
不要因为您不喜欢打字而走上使运算符超载的愚蠢路线。
例如 MyThingyList + SomeFileName 从文件加载 MyThingyList。
或
MyThingyList — 调用 MyThingsList.Clear()。
How to use them? Carefully.
They need to make sense.
E.g. Defining say a Type to hold a ComplexNumber or a Matrix and then overloading arithmetical operators makes sense.
Don't go down the foolish route of overloading an operator because you don't like typing.
e.g. MyThingyList + SomeFileName loads MyThingyList from the file.
or
MyThingyList-- calls MyThingsList.Clear().