contravariance

Why doesn't the example compile, aka how does (co-, contra-, and in-) variance work?

℡╲_俬逩灬. 提交于 2019-11-26 01:25:24
问题 Following on from this question, can someone explain the following in Scala: class Slot[+T] (var some: T) { // DOES NOT COMPILE // \"COVARIANT parameter in CONTRAVARIANT position\" } I understand the distinction between +T and T in the type declaration (it compiles if I use T ). But then how does one actually write a class which is covariant in its type parameter without resorting to creating the thing unparametrized ? How can I ensure that the following can only be created with an instance

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

冷暖自知 提交于 2019-11-26 00:14:37
问题 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<string> can be assigned to List<object> . How could that be? In Jon Skeet\'s book C# in Depth , it is explained why C# generics doesn\'t support covariance and contra-variance. It is mainly for writing secure code. Now, C# 4.0 changed to support them. Would it bring chaos? Anybody know the details about C# 4.0 can give some explanation? 回答1: Variance will

Difference between Covariance & Contra-variance

折月煮酒 提交于 2019-11-25 23:24:04
问题 I am having trouble understanding the difference between covariance and contravariance. 回答1: The question is "what is the difference between covariance and contravariance?" Covariance and contravariance are properties of a mapping function that associates one member of a set with another . More specifically, a mapping can be covariant or contravariant with respect to a relation on that set. Consider the following two subsets of the set of all C# types. First: { Animal, Tiger, Fruit, Banana }.

Why covariance and contravariance do not support value type

£可爱£侵袭症+ 提交于 2019-11-25 21:59:11
问题 IEnumerable<T> is co-variant but it does not support value type, just only reference type. The below simple code is compiled successfully: IEnumerable<string> strList = new List<string>(); IEnumerable<object> objList = strList; But changing from string to int will get compiled error: IEnumerable<int> intList = new List<int>(); IEnumerable<object> objList = intList; The reason is explained in MSDN: Variance applies only to reference types; if you specify a value type for a variant type