Multicast delegate weird behavior in C#?

前端 未结 4 1059
春和景丽
春和景丽 2020-12-10 23:57

I have this simple event :

public class ClassA
{
    public event Func Ev;
    public int Do(string l)
    {
        return Ev(l);
    }
}
         


        
4条回答
  •  执念已碎
    2020-12-11 00:22

    As a general rule, it doesn't make sense for events to return a value.

    If you want to get information from an event handler it makes more sense for the event handlers to mutate an input parameter, or just call another method of whatever object fired the event to communicate something else.

    Normally this doesn't even come up because events logically are passing information to the event handlers, and don't have any need to get information from the event handlers. It's honestly a sign of code smell. An event shouldn't care if anyone has subscribed to it, who they might be, what they might be doing, or even if there are any subscribers. Relying on a return value from them then just creates overly tight coupling.

提交回复
热议问题