猿问

在逆变中,引用的赋值兼容性被反转意味着什么?

在逆变中,引用的赋值兼容性被反转意味着什么?


协方差和逆变 (C#)


// Assignment compatibility.   

string str = "test";  

// An object of a more derived type is assigned to an object of a less derived type.   

object obj = str;  


// Covariance.   

IEnumerable<string> strings = new List<string>();  

// An object that is instantiated with a more derived type argument   

// is assigned to an object instantiated with a less derived type argument.   

// Assignment compatibility is preserved.   

IEnumerable<object> objects = strings;  


// Contravariance.             

// Assume that the following method is in the class:   

// static void SetObject(object o) { }   

Action<object> actObject = SetObject;  

// An object that is instantiated with a less derived type argument   

// is assigned to an object instantiated with a more derived type argument.   

// Assignment compatibility is reversed.   

Action<string> actString = actObject;

参考: https : //docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/


此外,当尝试从派生较少的类型转换为派生较多的类型时,InvalidCastException会抛出an 。由于用户定义的转换不允许进出基类,我看不出方法组的逆变是如何工作的 - 不会/不应该调用这样的方法InvalidCastException也会抛出一个?


更新:https : //blogs.msdn.microsoft.com/ericlippert/2009/11/30/whats-the-difference-between-covariance-and-assignment-compatibility/


互换的青春
浏览 168回答 2
2回答
随时随地看视频慕课网APP
我要回答