简体   繁体   中英

C# custom event handlers

If I have a property:

public list<String> names { get; set; }

How can I generate and handle a custom Event for arguments sake called 'onNamesChanged' whenever a name gets added to the list?

A BindingList is likely your best option as it has builtin change tracking and a variety of existing events you can use. Below is an example of exposing a custom event for Add which forwards to the BindingList event.


    class Example
    {
        private BindingList<string> m_names = new BindingList<string>();
        public IEnumerable<string> Names { get { return m_names; } }
        public event AddingNewEventHandler NamesAdded
        {
            add { m_names.AddingNew += value; }
            remove { m_names.AddingNew -= value; }
        }
        public void Add(string name)
        {
            m_names.Add(name);
        }
    }

您应该检出System.ComponentModel.BindingList ,尤其是ListChanged事件

BindingList的一种替代方法是ObservableCollection-在这种情况下,您希望将自己的事件处理程序订阅到CollectionChanged事件,并根据操作触发事件。

David Mohundro shows one approach; one other option is to inherit from Collection<T> and override the various methods:

class Foo {}
class FooCollection : Collection<Foo>
{
    protected override void InsertItem(int index, Foo item)
    {
        // your code...
        base.InsertItem(index, item);
    }
    protected override void SetItem(int index, Foo item)
    {
        // your code...
        base.SetItem(index, item);
    }
    // etc
}

Finally, you could create your own list (IList, IList<T>) from first principles - lots of work, little benefit.

A non-orthodox approach might be using an AOP framework such as PostSharp to "weave" a handler before/after the accessor is called, which fires an event.

You create an external class which contains the pre and/or post handling code for when your property is accessed, check if the value of the property changed between pre and post, and raise an event.

Bear in mind that while taking the value for comparison (inside your handler code), you might get into an infinite loop (you call the property accessor, which calls the AOP handler, which calls the accessor and so on), so you might need to reflect into the class containing this property to attain the backing field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM