我正在尝试在 C# 中使用等号 (==) 比较两个结构。我的结构如下:
public struct CisSettings : IEquatable<CisSettings>
{
public int Gain { get; private set; }
public int Offset { get; private set; }
public int Bright { get; private set; }
public int Contrast { get; private set; }
public CisSettings(int gain, int offset, int bright, int contrast) : this()
{
Gain = gain;
Offset = offset;
Bright = bright;
Contrast = contrast;
}
public bool Equals(CisSettings other)
{
return Equals(other, this);
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
var objectToCompareWith = (CisSettings) obj;
return objectToCompareWith.Bright == Bright && objectToCompareWith.Contrast == Contrast &&
objectToCompareWith.Gain == Gain && objectToCompareWith.Offset == Offset;
}
public override int GetHashCode()
{
var calculation = Gain + Offset + Bright + Contrast;
return calculation.GetHashCode();
}
}
我正在尝试将结构作为我的类中的一个属性,并想在我继续之前检查该结构是否等于我试图分配给它的值,所以我不是指示属性在未更改时已更改,如下所示:
public CisSettings TopCisSettings
{
get { return _topCisSettings; }
set
{
if (_topCisSettings == value)
{
return;
}
_topCisSettings = value;
OnPropertyChanged("TopCisSettings");
}
}
但是,在检查相等性的那一行,我得到了这个错误:
Operator '==' cannot be applied to operands of type 'CisSettings' and 'CisSettings'
我不明白为什么会这样,有人能给我指出正确的方向吗?
最佳答案
您需要重载 ==
和 !=
运算符。将此添加到您的 struct
:
public static bool operator ==(CisSettings c1, CisSettings c2)
{
return c1.Equals(c2);
}
public static bool operator !=(CisSettings c1, CisSettings c2)
{
return !c1.Equals(c2);
}
关于c# - 使用 == 比较两个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15199026/