通过比较两个结构== [英] Comparing two structs using ==

查看:119
本文介绍了通过比较两个结构==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用比较在C#中的equals(==)两个结构。我的结构是如下:

I am trying to compare two structs using equals (==) in C#. My struct is below:

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();
    }
}

我想有结构作为班里的属性,并要检查,看看是否该结构等于我想它分配给我继续前进,这样做之前的价值,所以我不表明属性已更改它不能当,像这样:

I am trying to have struct as a property in my class, and want to check to see if the struct is equal to the value I am trying to assign it to, before I go ahead and do so, so I am not indicating the property has changed when it hasn't, like so:

public CisSettings TopCisSettings
{
    get { return _topCisSettings; }
    set
    {
        if (_topCisSettings == value)
        {
            return;
        }
        _topCisSettings = value;
        OnPropertyChanged("TopCisSettings");
    }
}

不过,在这里我检查平等的线,我得到这个错误:

However, on the line where I check for equality, I get this error:

运营商'=='不能应用于类型的操作数'CisSettings和
  CisSettings

Operator '==' cannot be applied to operands of type 'CisSettings' and 'CisSettings'

我想不通为什么发生这种情况,可能有人点我在正确的方向?

I can't figure out why this is happening, could somebody point me in the right direction?

推荐答案

您需要重载 == != 运营商。添加到您的结构

You need to overload the == and != operators. Add this to your 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);
}

这篇关于通过比较两个结构==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆