Invocation of a polymorphic field-like event

后端 未结 1 1273
我寻月下人不归
我寻月下人不归 2021-01-01 11:14

Considering the code below:

public class TableMain {
    public virtual event Action UpdateFilter;
    ....
}

public class TableSub : TableMain {
    public         


        
相关标签:
1条回答
  • 2021-01-01 11:55

    Well, you've actually got two field-like events here. Your override will be overriding the add/remove part, but you'll have two fields - one in TableMain and one in TableSub. Only the one in TableSub will ever be non-null, unless the value is set explicitly in TableMain... so if TableMain ever tries to raise the event itself, it won't call the same set of handlers as in TableSub. Basically, it's going to behave strangely.

    The right approach is to provide a protected method in TableMain to allow the event to be raised by subclasses:

    protected void OnUpdateFilter()
    {
        Action handler = UpdateFilter;
        if (handler != null)
        {
            handler();
        }
    }
    

    Then make the event non-virtual, and remove the override in TableSub.

    Note that your event signature doesn't match the normal convention for events - any reason for not using EventHandler?

    0 讨论(0)
提交回复
热议问题