2013-03-04 74 views
38

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

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'

我不明白为什么这是发生,有人可以指出我在正确的方向吗?

+0

如何使用'等于()'? – 2013-03-04 10:12:02

+0

等于工作正常,只是想知道为什么我的重写==不工作 – JMK 2013-03-04 10:12:47

+3

@JMK,也许是因为你没有覆盖它... :) – gdoron 2013-03-04 10:13:24

回答

63

您需要超载==!=运营商。添加到您的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); 
} 
+0

我是个白痴,你是第一个,所以你得到最好的答案! – JMK 2013-03-04 10:14:56

+0

thx - 你几乎在那里。 – 2013-03-04 10:16:22

+2

@JMK,其实我是第一个,但我很酷。 :) – gdoron 2013-03-04 10:17:00

1

你应该超载运营一些方法是这样的:

public static bool operator ==(CisSettings a, CisSettings b) 
{ 
    return a.Equals(b); 
} 
1

你需要重写==操作符明确。

public static bool operator ==(CisSettings x, CisSettings y) 
{ 
    return x.Equals(y); 
} 

顺便说一句,你最好把比较的代码在public bool Equals(CisSettings other),并让bool Equals(object obj)呼叫bool Equals(CisSettings other),这样就可以得到避免不必要的类型检查的一些性能。