Multicast delegate weird behavior in C#?

前端 未结 4 1058
春和景丽
春和景丽 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:25

    The events are just iterated in the order they were attached. Because you are using a return value, the value you get is the last invoked.

    This is not really a normal pattern for events though. You probably want something a bit more like:

    public class MyEventArgs : EventArgs
    {
        public MyEventArgs()
        {
            Results = new List();
        }
        public string InputString{get;set;}
        public List Results{get;set;}
    }
    public event EventHandler Ev
    public int Do(string l)
    {
        MyEventArgs e = new MyEventArgs();
        e.InputString = l;
        if(Ev != null) Ev(this, e);
        return e.Results.Sum();
    }
    

    and then

    static int Display(object sender, MyEventArgs e)
            {
                return e.Results.Add(k.Length);
            }
    
      static int Display_2(object sender, MyEventArgs e)
            {
                return e.Results.Add(k.Length*10);
            }
    

提交回复
热议问题