为什么我们需要协方差? [英] Why do we need covariance?

查看:111
本文介绍了为什么我们需要协方差?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好.有人可以说明为什么我们需要协方差修饰符吗?只要有参考文献,它就应该可以正常工作.那么为什么要使用这些限制呢?

Hello. Could someone shed light on reasons why we need covariance modificators?  It should work perfectly as long as we have references. So why those restrictions?

推荐答案

Hi Booster,

Hi Booster,

这里是MSDN的样本.

Here is a sample from MSDN.

它们仅允许您执行一些在概念上有效且在形式上可以接受的事情.这使程序员的生活更轻松

They just allow you to do some things that are conceptually valid, and formally acceptable. This  make programmers' lives easier

// 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://msdn.microsoft.com/zh-CN/library/ee207183.aspx?f=255&MSPPError=-2147217396

For more details, please refer to https://msdn.microsoft.com/en-us/library/ee207183.aspx?f=255&MSPPError=-2147217396

最诚挚的问候,

克里斯汀


这篇关于为什么我们需要协方差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆