tôi đã xác định các giao diện sauLàm cách nào để ghi đè toán tử == cho Giao diện trong C#?
public interface IHaveAProblem
{
string Issue { get; set; }
}
Và đây là việc thực hiện các 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);
}
}
Khi tôi sử dụng đối tượng tôi có thể có được kết quả chính xác cho các == so sánh.
SomeProblem firstTest = new SomeProblem()
{
Issue = "Hello World"
};
SomeProblem secondTest = new SomeProblem()
{
Issue = "Hello World"
};
// This is true
bool result = firstTest == secondTest;
Tuy nhiên khi tôi cố gắng để so sánh các giao diện nó đang làm một bộ nhớ so sánh chứ không phải là toán tử == trên SomeProblem
IHaveAProblem firstProblem = new SomeProblem()
{
Issue = "Hello World"
};
IHaveAProblem secondProblem = new SomeProblem()
{
Issue = "Hello World"
};
Có thể có giao diện sử dụng == trên SomeProblem hơn một bộ nhớ so sánh?
Tôi biết mình có thể làm firstProblem.Equals(secondProblem)
và nhận kết quả phù hợp, tuy nhiên tôi đang tạo một tác phẩm khung và tôi sẽ không biết cách nó được sử dụng cuối cùng. Tôi nghĩ == sẽ hoạt động chính xác.
Có một cuộc thảo luận khá kỹ lưỡng về điều này tại đây. Tác giả dường như đã có một chút thời điểm bóng đèn liên quan đến một số giả định mà tôi nghĩ rằng bạn chia sẻ: http://stackoverflow.com/questions/728434/operator-overloading-with-interface-based-programming-in-c –