运算符重载和不同类型

Adr*_*ell 9 c#

我有一个课程分数,它将大量用于比较整数.我打算重载==运算符以根据下面的代码启用这些比较?

public class Score
{
    public Score(int score) {
        Value = score;
    }

    public static bool operator ==(Score x, int y) {
        return x != null && x.Value == y;
    }

    public static bool operator ==(int y, Score x)
    {
        return x != null && x.Value == y;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是运算符重载的明智用法吗?

我是否应该为操作员的LH和RH侧提供过载以允许使用对称?

Ant*_*ram 10

我可以继续定义从intto 的隐式转换Score,这样当你处理相等时,你只需要处理一个类型.

public static implicit operator Score(int value)
{
    return new Score { Value = value }; // or new Score(value);
}
// define bool operator ==(Score score1, Score score2)

// elsewhere 
Score score = new Score { Value = 1 };
bool isScoreOne = (score == 1);
Run Code Online (Sandbox Code Playgroud)

当你定义自己的==运算符时,请记住继续定义!=,覆盖EqualsGetHashCode.


ian*_*lly 5

我确实认为使用运算符重载是一种奇怪的情况,但这是您的要求。

但是,我的主要观点是,如果您超载==,您还需要超载!=

如果然后重载!=,则比较x以检查x是否为null的部分x != null将导致==运算符调用!=运算符。只要它不使用==比较,这本身就不是问题,因为您将有一组递归调用,从而导致堆栈溢出。

但是,由于很多人在重载!=时将其实现为'not =='-在您的情况下,这将导致堆栈溢出。

解决方案:特别是在重载==,!=和Equals()中,Object.ReferenceEquals(x, null);与null进行比较时最好使用。