在 C# 中,我们如何检查实现相等运算符的类型的引用相等性?
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
静态方法即使==
运算符已重载以使当前类型正常工作,否则:
Object.ReferenceEquals(obj1, obj2);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)