سؤال

I have a class called Message which overloads these operators:

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)

I want the == and != operators keep comparing references of the types other than String and Message but,

var message = new Message();
var isNull = message == null;

gives me this:

The call is ambiguous between the following methods or properties: 'Message.operator ==(Message, Message)' and 'Message.operator ==(Message, string)'

I know it's because both Message and String are reference types and they both can be null, but I want to be able to use == opreator for checking whether the message is null.

Can I overload == for null values? I tried overloading it for object and call object.ReferenceEquals(object, object) in the overload but that didn't help.

هل كانت مفيدة؟

المحلول

Provide an implementation for operator ==(Message left, object right) and check the type of right to see whether it is null, a string or a Message.

Alternatively, define an implicit constructor for Message that takes a string. See Operator overloading and different types for an example.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top