Event and delegate contravariance in .NET 4.0 and C# 4.0

后端 未结 4 1625
离开以前
离开以前 2020-12-09 02:45

While investigating this question I got curious about how the new covariance/contravariance features in C# 4.0 will affect it.

In Beta 1, C# seems to disagree with t

4条回答
  •  青春惊慌失措
    2020-12-09 03:23

    I just had to fix this in my application. I did the following:

    // variant delegate with variant event args
    MyEventHandler<(object sender, IMyEventArgs a)
    
    // class implementing variant interface
    class FiresEvents : IFiresEvents
    {
        // list instead of event
        private readonly List> happened = new List>();
    
        // custom event implementation
        public event MyEventHandler Happened
        {
            add
            {
                happened.Add(value);
            }
            remove
            {
                happened.Remove(value);
            }
        }
    
        public void Foo()
        {
            happened.ForEach(x => x.Invoke(this, new MyEventArgs(t));
        }
    }
    

    I don't know if there are relevant differences to regular multi-cast events. As far as I used it, it works ...

    By the way: I never liked the events in C#. I don't understand why there is a language feature, when it doesn't provide any advantages.

提交回复
热议问题