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

后端 未结 4 1627
离开以前
离开以前 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 03:15

    Very interesting. You don't need to use events to see this happening, and indeed I find it simpler to use simple delegates.

    Consider Func and Func. In C# 4.0 you can implicitly convert a Func to Func because you can always use a string reference as an object reference. However, things go wrong when you try to combine them. Here's a short but complete program demonstrating the problem in two different ways:

    using System;
    
    class Program
    {    
        static void Main(string[] args)
        {
            Func stringFactory = () => "hello";
            Func objectFactory = () => new object();
    
            Func multi1 = stringFactory;
            multi1 += objectFactory;
    
            Func multi2 = objectFactory;
            multi2 += stringFactory;
        }    
    }
    
    
    

    This compiles fine, but both of the Combine calls (hidden by the += syntactic sugar) throw exceptions. (Comment out the first one to see the second one.)

    This is definitely a problem, although I'm not exactly sure what the solution should be. It's possible that at execution time the delegate code will need to work out the most appropriate type to use based on the delegate types involved. That's a bit nasty. It would be quite nice to have a generic Delegate.Combine call, but you couldn't really express the relevant types in a meaningful way.

    One thing that's worth noting is that the covariant conversion is a reference conversion - in the above, multi1 and stringFactory refer to the same object: it's not the same as writing

    Func multi1 = new Func(stringFactory);
    
    
    

    (At that point, the following line will execute with no exception.) At execution time, the BCL really does have to deal with a Func and a Func being combined; it has no other information to go on.

    It's nasty, and I seriously hope it gets fixed in some way. I'll alert Mads and Eric to this question so we can get some more informed commentary.

    提交回复
    热议问题