名单< T>关于变更射击事件

名单< T>关于变更射击事件

问题描述:

我创建了一个类的 EVENTLIST 继承列表这触发一个事件,每次的东西被添加,插入或删除:

I created a Class EventList inheriting List which fires a Event each time something is Added, Inserted or Removed:

public class EventList<T> : List<T>
{
    public event ListChangedEventDelegate ListChanged;
    public delegate void ListChangedEventDelegate();

    public new void Add(T item)
    {
        base.Add(item);
        if (ListChanged != null
            && ListChanged.GetInvocationList().Any())
        {
            ListChanged();
        }
    }
    ...
}

目前我用它作为地产这样的时刻:

At the Moment I use it as Property like this:

public EventList List
{
    get { return m_List; }
    set
    {
        m_List.ListChanged -= List_ListChanged;

        m_List = value;

        m_List.ListChanged += List_ListChanged;
        List_ListChanged();
    }
}

现在我的问题是,我可以以某种方式处理,如果一个新的对象被吹罚给它或prevent这一点,所以我没有做事件连接东西在二传手?

Now my Problem is, can i somehow handle if a new Object is refereed to it or prevent that, so i do not have to do the event wiring stuff in the setter?

我当然可以改变属性为私订,但我想是能够使用类变量为好。

Of course i can change the property to "private set" but i would like to be able to use the class as variable as well.

您很少在一个类中创建一个集合类的新实例。实例化了一次,明确创建一个新的列表它代替。 (与使用的ObservableCollection,因为它已经有 INotifyCollectionChanged 接口继承)

You seldom create a new instance of a collection class in a class. Instantiate it once and clear it instead of creating a new list. (and use the ObservableCollection since it already has the INotifyCollectionChanged interface inherited)

private readonly ObservableCollection<T> list;
public ctor() {
    list = new ObservableCollection<T>();
    list.CollectionChanged += listChanged;
}

public ObservableCollection<T> List { get { return list; } }

public void Clear() { list.Clear(); }

private void listChanged(object sender, NotifyCollectionChangedEventArgs args) {
   // list changed
}

这样,您只需要挂钩的事件一次,可以通过调用明确的方法,而不是检查null或相等,前者列表中的set访问器属性复位。

This way you only have to hook up events once, and can "reset it" by calling the clear method instead of checking for null or equality to the former list in the set accessor for the property.