List < T > vs BindingList < T > Advantages/DisAdvantages

有人能描述一下我的项目中两者的区别吗。

目前我有一个 List<MyClass>,并将 BindingSource 设置为它,将 DataGridView 设置为 BindingSource。

我已经实现了 IEditableObject,所以当调用 CancelEdit 时,我将我的对象恢复到使用 Memberwise.Clone()时的状态

将 List 更改为 BindingList 能解决这些问题吗? 使用 BindingList 的优点是什么?

81511 次浏览

A BindingList allows two-way databinding by using events, a List does not fire events when its collection changes.

I don't think it will fix your particular problem.

A List<> is simply an automatically resizing array, of items of a given type, with a couple of helper functions (eg: sort). It's just the data, and you're likely to use it to run operations on a set of objects in your model.

A BindingList<> is a wrapper around a typed list or a collection, which implements the IBindingList interface. This is one of the standard interfaces that support two-way databinding. It works by implementing the ListChanged event, which is raised when you add, remove, or set items. Bound controls listen to this event in order to know when to refresh their display.

When you set a BindingSource's DataSource to a List<>, it internally creates a BindingList<> to wrap your list. You may want to pre-wrap your list with a BindingList<> yourself if you want to access it outside of the BindingSource, but otherwise it's just the same. You can also inherit from BindingList<> to implement special behavior when changing items.

IEditableObject is handled by the BindingSource. It'll call BeginEdit on any implementing object when you change the data in any bound control. You can then call EndEdit/CancelEdit on the BindingSource and it will pass it along to your object. Moving to a different row will call EndEdit as well.