2012-09-24 105 views
5

我有一個叫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) 

我想==!=運營商保持比StringMessage,但其他類型的比較基準,

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

給了我這樣的:

呼叫是下述方法或屬性之間曖昧:「Message.operator ==(消息,消息)」和「Message.operator ==(消息,字符串)」

我知道這是因爲這兩個MessageString是引用類型,他們都可以null,但我希望能夠使用== opreator檢查郵件是否爲空。

我可以重載==爲空值?我試圖重載它object,並呼籲在過載object.ReferenceEquals(object, object)但沒有幫助。

+3

如果你wan't做這樣(我不推薦),你將不得不投'null'適用的類型之一。 'message ==(string)null;'或'message ==(Message)null;'應該工作。 – verdesmarald

+0

@verdesmarald:是的,這有效,但我希望找到直接使用它的方法。你推薦什麼順便說一句? –

+0

不,據我所知,如果你想有多個'operator ==',你不能這麼做。 – verdesmarald

回答

6

提供operator ==(Message left, object right)的實現並檢查right的類型以查看它是否爲空,字符串或消息。

可替換地,限定用於消息接收字符串的隱式構造。一個例子見Operator overloading and different types