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

后端 未结 4 1622
离开以前
离开以前 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:13

    The following code actually works if you have the delegates normalized to the same type from within upon attaching/detaching! I didn't expect detaching to work but it does. It may not be the most optimized solution but it is clean and simple and it solves a serious problem I've had with my Foundation where co-variance is important for example IObservableList : IObservableListOut. At some point extensions created different delegate types depending on context T where T can be 2 different interfaces per context and therefore the delegates created ended up of different type. It wasn't until today that I actually understood how this issue resulted. Detaching won't work with plain "- value".

        private event MyEventHandler happened;
        public event MyEventHandler Happened
        {
            add => this.happened += new MyEventHandler(value);
            remove => this.happened -= new MyEventHandler(value);
        }
    

提交回复
热议问题