How can we check reference equality for a type that implements equality operator?

a 夏天 提交于 2019-12-31 07:24:07

问题


In C#, how can we check reference equality for a type that implements equality operator?

class C
{
    public int Val{get;set;}
    public static bool operator ==(C c1, C c2)
    {
        return c1.Val == c2.Val;
    }
    public static bool operator !=(C c1, C c2)
    {
        return c1.Val != c2.Val;
    }
}
class Program
{
    public static void Main(string[] args)
    {
        C c1=new C(){Val=1};
        C c2=new C(){Val=1};
        Console.WriteLine(c1==c2);//True. but they are not same objects. 
                                  //How can I Check that?
        Console.Write("Press any key to continue . . . ");
    }
}

回答1:


If you mean equality by reference, you may use the Object.ReferenceEquals static method even if the == operator was overloaded for the current type to work otherwise:

Object.ReferenceEquals(obj1, obj2);



回答2:


What does object "object equality"?

If by "how can we check object equality for a type that implements equality operator?", you actually mean "how can we check object equality for a type that implements IEquatable<T>", the short answer is...however you want (with some caveats).

The documentation for IEquatable<T> offers some guidelines. You might also want to implement IComparable<T> as well. And if you implement both IEquatable<T> and IComparable<T>, it would make sense if your Equals() method returns true for all the cases where your CompareTo() method returns 0, and for your Equals() method to return false for all the cases where your CompareTo() method returns a non-zero value.

Further, you might want to ensure that you properly override == and != to provide the same behaviour as calling Equals().



来源:https://stackoverflow.com/questions/20361821/how-can-we-check-reference-equality-for-a-type-that-implements-equality-operator

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