简体   繁体   English

.net运算符重载

[英].net Operator Overloading

Why is it required on some operators Eg the comparison operators. 为什么某些运算符需要它,例如比较运算符。

<   <=   >   >=   =  <>

You have to also implement their complement also? 您还必须实施它们的补充吗?

<  >=

What is restrict your object implementing just 什么限制了您的对象仅实现

<

if that has specific meaning to it, and 如果它具有特定含义,并且

>= 

doesn't

Note: The workaround I've is to stick the Obsolete attribute on the unwanted operator. 注意:我要解决的方法是将过时属性粘贴到不需要的运算符上。

Operator overloading in .Net (at least for C# and VB) is intentionally less flexible than operator overloading in C++. .Net中的运算符重载(至少对于C#和VB而言)故意不如C ++中的运算符重载灵活。

One reason that Java went so far as to remove overloading entirely is that too many developers abused overloading to do clever-looking things that confused other developers and broke core assumptions of generic algorithms that expect to be able to, say, reasonably compare two instances of a user type. Java之所以能够完全消除重载,是因为太多的开发人员滥用重载来做看起来聪明的事情,这使其他开发人员感到困惑,并打破了通用算法的核心假设,这些假设可以合理地比较两个实例。用户类型。

While .Net brought back some flexibility, the designers were careful to only allow overloading of certain operators with the intent that they only be used for their customary meanings. 虽然.Net带来了一定的灵活性,但设计人员还是谨慎地仅允许某些运算符重载,目的是使它们仅用于其惯常含义。

The requirement to implement comparison operators symmetrically is a nod to that intention. 对称地实现比较运算符的要求就是对此的致意。

If you want to do more aggressive operator overloading, I'd encourage you to consider using F#, where you have access to a much broader palette of symbols with which to draw clever operator symbols. 如果您想进行更激进的运算符重载,建议您考虑使用F#,在此您可以使用更广泛的符号调色板来绘制聪明的运算符。

Presumably because if you overload one side of an operator, you are implementing some custom rule, and the default operator would not match your rule, and thus produce odd behaviours. 大概是因为如果您重载运算符的一侧,那么您正在实现某些自定义规则,而默认运算符将与您的规则不匹配,从而产生奇怪的行为。

For example, if your definition of 'int >' was 'return (x > 5);' 例如,如果您对“ int>”的定义为“ return(x> 5);”。 (for some reason...) and you didn't overlaod the inverse rule for the 'int <' operator, then; (由于某种原因...),那么您并没有覆盖'int <'运算符的逆规则。

4 > 1 would be false (by your rule), but 4 < 1 would also be false (by the default rule). 4> 1将是假的(由规则),但4 <1 将是假的(由默认规则)。

Which is illogical, Jim. 吉姆,这不合逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM