ObjectCollection.Add(item)是否调用item.Equals()?
在CheckedListBox
上找到了Form
,并尝试添加一些项目。但是我发现调用CheckedListBox.Items.Add(item)
时会调用item.Equals()
。
另外,我发现item.GetHashCode()
也被调用了。对于为什么会发生感到非常困惑。
代码如下。
List<Person> people = new List<Person>();//Person is a customer class for test.
people.Add(new Person() { Name = "张三", Id = "201411580572", Gender = "Male" });
people.Add(new Person() { Name = "李四", Id = "201411580573", Gender = "Male" });
people.Add(new Person() { Name = "王武", Id = "201411580574", Gender = "Male" });
people.Add(new Person() { Name = "赵柳", Id = "201411580575", Gender = "Male" });
people.Add(new Person() { Name = "张飞", Id = "201411580576", Gender = "Male" });
people.Add(new Person() { Name = "赵云", Id = "201411580577", Gender = "Male" });
cklTest.DisplayMember = "Name";//cklTest is a CheckedListBox.
people.ForEach(p => cklTest.Items.Add(p));
修改:
答案 0 :(得分:2)
您的呼叫堆栈显示该呼叫来自Formatter.FormatObject
,后者依次呼叫Formatter.IsNullData
。
public static bool IsNullData(object value, object dataSourceNullValue) {
return value == null ||
value == System.DBNull.Value ||
Object.Equals(value, NullData(value.GetType(), dataSourceNullValue));
}
我们看到了对Object.Equals
的调用,以检查您的对象是否等于dataSourceNullValue
(代表空数据的自定义值)。有趣的是,在这种情况下dataSourceNullValue为DBNull.Value
,因此上述检查是多余的。但是您对此无能为力。
如果您不希望在此代码路径上调用Equals,则可以通过将FormattingEnabled
设置为false来解决。这将导致CheckedListBox使用an alternative way格式化对象:
if (!formattingEnabled) {
// Microsoft gave his blessing to this RTM breaking change
if (item == null) {
return String.Empty;
}
item = FilterItemOnProperty(item, displayMember.BindingField);
return (item != null) ? Convert.ToString(item, CultureInfo.CurrentCulture) : "";
}