【发布时间】:2011-05-13 23:58:00
【问题描述】:
我们为我们的 CMS 设置了几个类,我正在尝试让平等工作,以便我可以检查通用列表是否包含项目。我们有一些继承层,我将在下面向您展示。在此之下,我将向您展示一些行为与我的预期相反的示例代码。如果您发现我做错了什么,请告诉我。我已经减少了下面的示例,只是为了向您展示相关的部分。我的实际课程要大得多,但我认为这是你需要看到的一切。
IBaseTemplate.cs
public interface IBaseTemplate {
bool Equals(IBaseTemplate other);
string GUID { get; }
}
BasePage.cs
public class BasePage : System.Web.UI.Page, IBaseTemplate, IEquatable<IBaseTemplate> {
// code to define properties, including GUID
// various constructors
public BasePage(string GUID) {
this.GUID = GUID;
}
// interface methods
public bool Equals(IBaseTemplate other) {
return (this.GUID == other.GUID);
}
}
LandingPage.cs
public class LandingPage : BasePage {
// a bunch of extra properties and method specific to LandingPage
// but NO definition for Equals since that's taken care of in BasePage
public LandingPage(string GUID) : base(GUID) {}
}
SamplePage.aspx.cs
var p1 = new LandingPage("{3473AEF9-7382-43E2-B783-DB9B88B825C5}");
var p2 = new LandingPage("{3473AEF9-7382-43E2-B783-DB9B88B825C5}");
var p3 = new LandingPage("{3473AEF9-7382-43E2-B783-DB9B88B825C5}");
var p4 = new LandingPage("{3473AEF9-7382-43E2-B783-DB9B88B825C5}");
var coll = new List<LandingPage>();
coll.Add(p1);
coll.Add(p2);
coll.Add(p3);
p1.Equals(p4); // True, as expected
coll.Contains(p4); // False, but I expect True here!
我希望coll.Contains(p4) 返回true,因为即使p1 到p4 是不同的实例,从BasePage 继承的Equals 方法会根据IBaseTemplate 的要求比较它们的GUID 属性。我错过了什么吗?
我查看了docs for List(T)'s Contains method,我正在实现IEquatable<T>.Equals,其中T 是IBaseTemplate。
【问题讨论】:
-
你应该可以在 Equals 方法中设置断点来查看值,你试过吗?
标签: c# equals contains generic-list iequatable