我有一个名为Message
的类,重载了以下运算符:
public static bool operator ==(Message left, Message right)
public static bool operator !=(Message left, Message right)
public static bool operator ==(Message left, string right)
public static bool operator !=(Message left, string right)
public static bool operator ==(string left, Message right)
public static bool operator !=(string left, Message right)
我希望
==
和!=
运算符在比较除了String
和Message
之外的类型的引用时仍然有效。var message = new Message();
var isNull = message == null;
这是我的代码:
调用的方法或属性模糊不清:'Message.operator ==(Message, Message)' 和 'Message.operator ==(Message, string)'
我知道这是因为Message
和String
都是引用类型,它们都可以是null
,但我想使用==
运算符来检查消息是否为null
。
我能否为null
值重载==
? 我尝试为object
重载它并在重载中调用object.ReferenceEquals(object, object)
,但这没有帮助。
null
强制转换为适用的类型之一。message == (string)null;
或者message == (Message)null;
应该可以工作。 - verdesmaraldoperator==
,则不能这样做。 - verdesmarald