运算符重载和不同类型 [英] Operator overloading and different types
问题描述
我有一个Score类,将在与整数的比较中大量使用.我打算重载==运算符,以按照下面的代码启用这些比较?
I have a class Score which is going to be heavily used in comparisons against integers. I was planning on overloading the == operator to enable these comparisons as per the code below ?
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;
}
}
这是对运算符重载的明智使用吗?
Is this a sensible use of operator overloading ?
我应该为操作员的左,右端提供重载,以使用法对称吗?
Should I be providing overloads for the LH and RH sides of the operators to allow the usage to be symmetrical ?
推荐答案
我可能会继续定义从 int
到 Score
的隐式转换,以便当您处理平等,您只需要处理一种类型.
I might go ahead and define an implicit conversion from int
to Score
, so that when you deal with equality, you only need to deal with a single type.
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);
在定义自己的 ==
运算符时,请记住继续定义!=
,并覆盖 Equals
和 GetHashCode
.
And while you're defining your own ==
operator, do remember to go ahead and define !=
, and override Equals
and GetHashCode
.
这篇关于运算符重载和不同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!