== 演算子の 2 つのオーバーライドを持つクラスがあり、このクラスの他のインスタンスと比較し、文字列のインスタンスと比較します。
class SomeClass
{
string value;
public SomeClass (string _Value)
{
value = _Value;
}
static public bool operator == (SomeClass C1, SomeClass C2)
{
return C1.value == C2.value;
}
static public bool operator != (SomeClass C1, SomeClass C2)
{
return C1.value != C2.value;
}
static public bool operator == (SomeClass C1, string C2)
{
return C1.value == (string) C2;
}
static public bool operator != (SomeClass C1, string C2)
{
return C1.value != (string) C2;
}
}
ただし、このクラスを null と比較しようとすると、次のようになります。
Console.WriteLine(someObject == null);
次のエラーが表示されます。
Error CS0121: The call is ambiguous between the following methods or properties: `SomeClass.operator ==(SomeClass, SomeClass)' and `SomeClass.operator ==(SomeClass, string)'
このクラスのインスタンスを null チェックできるように、== オーバーライドをどのように定義すればよいですか?