本文介绍了我们如何检查实现相等运算符的类型的引用相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中,我们如何检查实现相等运算符的类型的引用相等性?
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 . . . ");
}
}
推荐答案
如果意思是指引用相等,即使 ==
运算符已重载,也可以使用 Object.ReferenceEquals
静态方法当前类型可以正常工作:
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);
这篇关于我们如何检查实现相等运算符的类型的引用相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!