名单< T>关于变更射击事件 [英] List<T> firing Event on Change

查看:149
本文介绍了名单< 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,因为它已经有<一个href="http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx"相对=nofollow> 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.

这篇关于名单&LT; T&GT;关于变更射击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆