简体   繁体   English

如何纠正规则'运算符重载已在c#中命名替换'

[英]How to correct the rule 'Operator overloads have named alternates' in c#

As the operator overloading (operator> and operator<) violates the rule Operator overloads have named alternates , the operator > and < require an alternative method Compare, however, since there can only be one Compare method, what should the signature of that method be? 由于运算符重载(运算符>和运算符<)违反规则运算符重载已命名为替换 ,运算符>和<需要替代方法比较,但是,因为只能有一个比较方法,该方法的签名应该是什么?

for example, I have: 例如,我有:

public static bool operator >(XXX lhs, XXX rhs)

and

public static bool operator <(XXX lhs, XXX rhs)

How to provide a compare method to behave the same as both greater to and less than operators? 如何提供一种比较方法,使其与大于和小于运算符的行为相同?

Edit: 编辑:

The int Compare() only returns positive (greater than), negative (less than) and 0 (equal), what about in my overloaded operator there is a >= operator, which means my Compare method should handle (greater to or equal to) sinario as well int Compare()只返回正(大于),负(小于)和0(等于),在我的重载运算符中有一个> =运算符,这意味着我的Compare方法应该处理(大于或等于也是sinario

What about there are >, < >= and <= four overloaded operators? 怎么样有>,<> =和<=四个重载运算符?

public static int Compare(XXX lhs, XXX rhs);

Return value: 返回值:

  • Less than zero 小于零
    lhs is less than rhs . lhs小于rhs
  • Zero
    lhs equals rhs . lhs等于rhs
  • Greater than zero 大于零
    lhs is greater than rhs . lhs大于rhs

Examples: 例子:

Usage: 用法:

// operator            // named alternative
   x < y                  Compare(x, y) < 0
   x <= y                 Compare(x, y) <= 0
   x > y                  Compare(x, y) > 0
   x >= y                 Compare(x, y) >= 0

Implementing IComparable<T> is also a good idea. 实现IComparable <T>也是一个好主意。

You have one Compare method, and the return value determines whether the 2 operands are equal (0), or if x is less than y, or if x is greater than y. 您有一个Compare方法,返回值确定2个操作数是否相等(0),或者x是否小于y,或者x是否大于y。

Check out the String.Compare method , for instance. 例如,查看String.Compare方法。

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

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