C# ObjectCollection.Add()是如何工作的

C# ObjectCollection.Add()是如何工作的,c#,winforms,C#,Winforms,ObjectCollection.Additem是否调用item.Equals? 在窗体上获取CheckedListBox,并尝试添加一些项。但我发现当调用CheckedListBox.Items.Additem时,它会调用item.Equals。 另外,我发现item.GetHashCode也被调用了。我很困惑为什么会这样。 代码如下 List<Person> people = new List<Person>();//Person is a customer clas

ObjectCollection.Additem是否调用item.Equals? 在窗体上获取CheckedListBox,并尝试添加一些项。但我发现当调用CheckedListBox.Items.Additem时,它会调用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));
编辑:


您的调用堆栈显示该调用来自Formatter.Formatter对象,而Formatter.IsNullData反过来又调用Formatter.IsNullData

是:

我们看到了对Object.Equals的调用,它检查您的对象是否等于dataSourceNullValue—一个表示空数据的自定义值。有趣的是,在此上下文中,dataSourceNullValue是DBNull.Value,因此检查与上面的检查是冗余的。但是你对此无能为力

如果您不希望在此代码路径上调用Equals,可以通过将FormattingEnabled设置为false来解决问题。这将导致CheckedListBox用于格式化对象:

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) : "";
}

您是如何发现调用了equals的?数据绑定可能会调用这些方法来确定要向用户显示的内容。这应该不是问题。为什么不使用AddRange而不是ForEach方法呢?显示如果ListControl被排序,它需要找到插入位置。您可以尝试在CheckedListBox上将FormattingEnabled设置为false吗?
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) : "";
}