我创建了一个具有==运算符功能的类,但是我想测试这些值是否为null,但是当我测试这个时,我开始一个永无止境的循环。如何在不创建永无止境的循环的情况下执行以下操作?
public struct MyClass
{
private string Value;
public static bool operator ==(MyClass left, MyClass right)
{
if (left == null && right == null)
return true;
if (left == null || right == null)
return false;
return left.Equals(right);
}
}
答案 0 :(得分:1)
找到答案
public struct MyClass
{
private string Value;
public static bool operator ==(MyClass left, object right)
{
// Test if both are null or the same instance, then return true
if (ReferenceEquals(left, right))
return true;
// If only one of them null return false
if (((object)left == null) || ((object)right == null))
return false;
// Test value
return left.Equals(right);
}
}