c# - 使用 == 比较两个结构

标签 c# struct equality

我正在尝试在 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/

相关文章:

c# - LINQ 中的双重过滤

c - 使用 & 运算符时 scanf() 中发生了什么?

c - C 结构体中的位域表达式

c++ - 比较两个(非 STL) map 是否相等

python - 什么时候用==,什么时候用is?

c# - 使用 REST XML Web 服务

c# - 使用默认设置 C# 以编程方式将应用程序添加到 IIS

c# - 从顺序文件读取到结构数组

comparison - 为什么有这么多方法来比较是否相等?

c# - 如何将一个 Int64 解码回两个 Int32?