Events of a non-delegate type

前端 未结 4 454
一生所求
一生所求 2021-01-03 03:27

I\'ve implemented a class that looks like this interface:

[ImmutableObject(true)]
public interface ICustomEvent
{
    void Invoke(object sender, EventArgs e)         


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-03 04:13

    If you want to be able to add and remove CustomEvent objects from the event (instead of regular delegates), there are two options:

    Make an implicit cast from ICustomEvent to EventHandler (or some other delegate) that returns an instance method of ICustomEvent (probably Invoke), then use the Target property of the delegate to get the original ICustomEvent in the add and remove accessors.

    EDIT: Like this:

    CustomEvent myEvent;
    public event EventHandler MyEvent {
        add {
            if (value == null) throw new ArgumentNullException("value");
            var customHandler = value.Target as ICustomEvent;
    
            if (customHandler != null)
                myEvent = myEvent.Combine(customHandler);
            else
                myEvent = myEvent.Combine(value);   //An ordinary delegate
        }
        remove {
            //Similar code
        }
    }
    

    Note that you'll still need to figure out how to add the first handler if it's a delegate (if the myEvent field is null)


    Make a writable property of type CustomEvent, then overload the + and - operators to allow += and -= on the property.

    EDIT: To prevent your callers from overwriting the event, you could expose the previous value in CustomEvent (I'm assuming it works like an immutable stack) and, in the setter, add

    if (myEvent.Previous != value && value.Previous != myEvent)
        throw new ArgumentException("You cannot reset a CustomEvent", "value");
    

    Note that when the last handler is removed, both value and myEvent.Previous will be null.

提交回复
热议问题