【发布时间】:2013-02-18 09:24:00
【问题描述】:
我正在尝试在 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();
}
}
我正在尝试将 struct 作为我的类中的一个属性,并想检查该 struct 是否等于我尝试分配给它的值,然后再继续这样做,所以我不是指示属性已更改,但未更改,如下所示:
public CisSettings TopCisSettings
{
get { return _topCisSettings; }
set
{
if (_topCisSettings == value)
{
return;
}
_topCisSettings = value;
OnPropertyChanged("TopCisSettings");
}
}
但是,在我检查相等的那一行,我得到了这个错误:
运算符“==”不能应用于“CisSettings”类型的操作数和 'CisSettings'
我不知道为什么会这样,有人能指出正确的方向吗?
【问题讨论】:
-
@JMK,也许是因为你没有覆盖它...... :)
-
if (obj == null || GetType() != obj.GetType())是一种很奇怪的写法if(!(obj is CisSettings))。 -
另外,逻辑放错了地方:将特定类型的逻辑放在
Equals(CisSettings)并让Equals(object)调用它,而不是反过来。 -
另外,在 32 位整数上调用
GetHashCode是不必要的;一个 32 位整数是它自己的哈希码。 -
另外,如果四个数字的值相似,您的哈希码分布就会很差。