为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
互换的青春 2021-07-14 13:05:19
在逆变中,引用的赋值兼容性被反转意味着什么?协方差和逆变 (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/
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 167 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信