Comparing two structs using ==

北城余情 提交于 2019-11-29 13:06:56
Jens Kloster

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

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 ==.

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

You should overload your operator is some way like this:

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

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.

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

For overloading operator, see this page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!