私は、次のインターフェースにC#のインターフェイスでequals演算子==をオーバーライドするにはどうすればよいですか?
public interface IHaveAProblem
{
string Issue { get; set; }
}
を定義し、ここで私は、私は==の正しい結果を比較する得ることができますオブジェクトを使用する場合IHaveAProblem
public class SomeProblem : IHaveAProblem
{
public string Issue { get; set; }
public override bool Equals(object obj)
{
SomeProblem otherObj = obj as SomeProblem;
if (otherObj == null)
{
return false;
}
return this.Issue == otherObj.Issue;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static bool operator ==(SomeProblem rhs, SomeProblem lhs)
{
// Null check
if (Object.ReferenceEquals(rhs, null) || Object.ReferenceEquals(lhs, null))
{
if (Object.ReferenceEquals(rhs, null) && Object.ReferenceEquals(lhs, null))
{
// Both are null. They do equal each other
return true;
}
// Only 1 is null the other is not so they do not equal
return false;
}
return rhs.Equals(lhs);
}
public static bool operator !=(SomeProblem rhs, SomeProblem lhs)
{
// Null check
if (Object.ReferenceEquals(rhs, null) || Object.ReferenceEquals(lhs, null))
{
if (Object.ReferenceEquals(rhs, null) && Object.ReferenceEquals(lhs, null))
{
// Both are null. They do equal each other
return false;
}
// Only 1 is null the other is not so they do not equal
return true;
}
return !rhs.Equals(lhs);
}
}
の実装ですしています。私はそれがメモリをやっているのインターフェイスを比較しようとすると、
SomeProblem firstTest = new SomeProblem()
{
Issue = "Hello World"
};
SomeProblem secondTest = new SomeProblem()
{
Issue = "Hello World"
};
// This is true
bool result = firstTest == secondTest;
しかしSomeProblemに==演算子のではなく、比較
IHaveAProblem firstProblem = new SomeProblem()
{
Issue = "Hello World"
};
IHaveAProblem secondProblem = new SomeProblem()
{
Issue = "Hello World"
};
はそれが可能インターフェースがではなくSomeProblemに==を使用する必要がありですメモリを比較する?
私はfirstProblem.Equals(secondProblem)
を実行して適切な結果を得ることができますが、フレームワークを作成していますが、最終的にどのように使用されるのかわかりません。私は==が正しく動作すると思った。
ここではかなり徹底的な議論があります。作者は、あなたが共有していると思ういくつかの前提に関する電球の瞬間が少しあるようです:http://stackoverflow.com/questions/728434/operator-overloading-with-interface-based-programming-in-c –