Comparing two structs using ==

前端 未结 6 847
萌比男神i
萌比男神i 2020-12-11 00:29

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

public struct CisSettings : IEquatable
{
    public int Ga         


        
相关标签:
6条回答
  • 2020-12-11 00:37

    you must overload "==" operator, but also overload "!=" operator. (Look at this Note)

    For overloading operator, see this page

    0 讨论(0)
  • 2020-12-11 00:40

    When you override the .Equals method, the == operator isn't automatically overloaded. You need to do that explicitly.

    See also Guidelines for Overriding Equals() and Operator ==.

    0 讨论(0)
  • 2020-12-11 00:41

    You should overload your operator is some way like this:

    public static bool operator ==(CisSettings a, CisSettings b)
    {
        return a.Equals(b);
    }
    
    0 讨论(0)
  • 2020-12-11 00:47

    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);
    }
    
    0 讨论(0)
  • 2020-12-11 00:54

    You don't implement explicitly an equality operator, so == is not defined particularly for the type.

    0 讨论(0)
  • 2020-12-11 01:03

    You need to override operator == explicitly.

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

    By the way, you'd better put the comparing code in public bool Equals(CisSettings other), and let bool Equals(object obj) call bool Equals(CisSettings other), so that you can gain some performance by avoiding unnecessary type check.

    0 讨论(0)
提交回复
热议问题