How is Generic Covariance & Contra-variance Implemented in C# 4.0?

后端 未结 2 515
别跟我提以往
别跟我提以往 2020-11-22 11:14

I didn\'t attend PDC 2008, but I heard some news that C# 4.0 is announced to support Generic covariance and contra-variance. That is, List can be

2条回答
  •  时光取名叫无心
    2020-11-22 12:00

    Variance will only be supported in a safe way - in fact, using the abilities that the CLR already has. So the examples I give in the book of trying to use a List as a List (or whatever it was) still won't work - but a few other scenarios will.

    Firstly, it will only be supported for interfaces and delegates.

    Secondly, it requires the author of the interface/delegate to decorate the type parameters as in (for contravariance) or out (for covariance). The most obvious example is IEnumerable which only ever lets you take values "out" of it - it doesn't let you add new ones. That will become IEnumerable. That doesn't hurt type safety at all, but lets you return an IEnumerable from a method declared to return IEnumerable for instance.

    Contravariance is harder to give concrete examples for using interfaces, but it's easy with a delegate. Consider Action - that just represents a method which takes a T parameter. It would be nice to be able to convert seamlessly use an Action as an Action - any method which takes an object parameter is going to be fine when it's presented with a string instead. Of course, C# 2 already has covariance and contravariance of delegates to some extent, but via an actual conversion from one delegate type to another (creating a new instance) - see P141-144 for examples. C# 4 will make this more generic, and (I believe) will avoid creating a new instance for the conversion. (It'll be a reference conversion instead.)

    Hope this clears it up a bit - please let me know if it doesn't make sense!

    提交回复
    热议问题