Covariance and Contravariance (C#)
Covariance and Contravariance (C#)
In C#, covariance and contravariance enable implicit reference conversion for array types, delegate types, and generic type arguments.
Covariance preserves assignment compatibility and contravariance reverses it.
The following code demonstrates the difference between assignment compatibility, covariance, and contravariance.
// 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;
public delegate void Action<in T>(T obj) Action的泛型委托,里面的T指定了是逆变的,本来的返回值类型是object的。现在范围缩小成string,不会影响程序的运行。
Covariance for arrays enables implicit conversion of an array of a more derived type to an array of a less derived type.
But this operation is not type safe, as shown in the following code example.
object[] array = new String[];
// The following statement produces a run-time exception.
// array[0] = 10;
Covariance and contravariance support for method groups allows for matching method signatures with delegate types.
This enables you to assign to delegates not only methods that have matching signatures, but also methods that return more derived types (covariance) or that accept parameters that have less derived types (contravariance) than that specified by the delegate type.
For more information, see Variance in Delegates (C#) and Using Variance in Delegates (C#).
The following code example shows covariance and contravariance support for method groups.
static object GetObject() { return null; }
static void SetObject(object obj) { }
static string GetString() { return ""; }
static void SetString(string str) { }
static void Test()
{
// Covariance. A delegate specifies a return type as object,
// but you can assign a method that returns a string.
Func<object> del = GetString;
// Contravariance. A delegate specifies a parameter type as string,
// but you can assign a method that takes an object.
Action<string> del2 = SetObject;
}
In .NET Framework 4 or newer C# supports covariance and contravariance in generic interfaces and delegates and allows for implicit conversion of generic type parameters.
For more information, see Variance in Generic Interfaces (C#) and Variance in Delegates (C#).
The following code example shows implicit reference conversion for generic interfaces.
IEnumerable<String> strings = new List<String>();
IEnumerable<Object> objects = strings;
A generic interface or delegate is called variant if its generic parameters are declared covariant or contravariant.
C# enables you to create your own variant interfaces and delegates.
For more information, see Creating Variant Generic Interfaces (C#) and Variance in Delegates (C#).
Covariance and Contravariance in Generics
http://msdn.microsoft.com/en-us/library/dd799517.aspx
Covariance and contravariance are terms that refer to the ability to use a less derived (less specific) or more derived type (more specific) than originally specified.
Generic type parameters support covariance and contravariance to provide greater flexibility in assigning and using generic types.
When you are referring to a type system, covariance, contravariance, and invariance have the following definitions.
The examples assume a base class named Base and a derived class named Derived.
Covariance 协变Enables you to use a more derived type than originally specified.
You can assign an instance of
IEnumerable<Derived>(IEnumerable(Of Derived)in Visual Basic) to a variable of typeIEnumerable<Base>.Contravariance 逆变Enables you to use a more generic (less derived) type than originally specified.
You can assign an instance of
IEnumerable<Base>(IEnumerable(Of Base)in Visual Basic) to a variable of typeIEnumerable<Derived>.Invariance 不变性,恒定性Means that you can use only the type originally specified; so an invariant generic type parameter is neither covariant nor contravariant.
You cannot assign an instance of
IEnumerable<Base>(IEnumerable(Of Base)in Visual Basic) to a variable of typeIEnumerable<Derived>or vice versa.
Covariant type parameters enable you to make assignments that look much like ordinary Polymorphism, as shown in the following code.
Covariance and Contravariance (C#)的更多相关文章
- Covariance and Contravariance in C#, Part One
http://blogs.msdn.com/b/ericlippert/archive/2007/10/16/covariance-and-contravariance-in-c-part-one.a ...
- Covariance and Contravariance in C#, Part Two: Array Covariance
http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-a ...
- 协变(covariance),逆变(contravariance)与不变(invariance)
协变,逆变与不变 能在使用父类型的场景中改用子类型的被称为协变. 能在使用子类型的场景中改用父类型的被称为逆变. 不能做到以上两点的被称为不变. 以上的场景通常包括数组,继承和泛型. 协变逆变与泛型( ...
- C#(转自wiki)
C#是微软推出的一种基于.NET框架的.面向对象的高级编程语言.C#的发音为"C sharp",模仿音乐上的音名"C♯"(C调升),是C语言的升级的意思.其正确 ...
- C#的变迁史 - C# 4.0篇
C# 4.0 (.NET 4.0, VS2010) 第四代C#借鉴了动态语言的特性,搞出了动态语言运行时,真的是全面向“高大上”靠齐啊. 1. DLR动态语言运行时 C#作为静态语言,它需要编译以后运 ...
- Adaptive Code Via C#读书笔记
原书链接: http://www.amazon.com/Adaptive-Code-via-principles-Developer-ebook/dp/B00OCLLYTY/ref=dp_kinw_s ...
- Nemerle Quick Guide
This is a quick guide covering nearly all of Nemerle's features. It should be especially useful to a ...
- [你必须知道的.NET]第三十一回,深入.NET 4.0之,从“新”展望
发布日期:2009.05.22 作者:Anytao © 2009 Anytao.com ,Anytao原创作品,转贴请注明作者和出处. /// <summary> /// 本文开始,将以& ...
- Visual C#每一次新版本的变化
What's New in Visual C# .NET 2003[Visual Studio .NET 2003] What's New in Visual C# 2005 What's New i ...
随机推荐
- HDU_5527_Too Rich
Too Rich Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total ...
- MySQL exists 和 not exists 的用法
有一个查询如下: 1 SELECT c.CustomerId, c.CompanyName 2 FROM Customers c 3 WHERE EXISTS( 4 SELECT ...
- C#中字符数组,字节数组和string之间的转化
转自:http://blog.csdn.net/wangxiaoqin00007/article/details/17675419 NDC(NetworkDiskClient)的界面和后台程序之间用S ...
- 找新朋友---hdu1286(欧拉函数)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1286 欧拉函数:对正整数n,欧拉函数是求少于n的数中与n互质的数的数目: 素数(质数)指在一个大于1的 ...
- 10张Gif动图让你弄懂递归等概念
图像(包括动图)是传递信息的一种高效方式,往往能增强表象.记忆与思维等方面的反应强度.所谓一图胜千言,说的就是这个道理. 今天为大家整理了十张动图GIFS,有助于认识循环.递归.二分检索等概念的具体运 ...
- java-mybaits-00601-查询缓存-一级缓存、二级缓存
1.什么是查询缓存 mybatis提供查询缓存,用于减轻数据压力,提高数据库性能. mybaits提供一级缓存,和二级缓存. 一级缓存是SqlSession级别的缓存. 在操作数据库时需要构造 sql ...
- Oracle扩容表空间
1.程序报错,无法进行修改操作,通过日志,看到如下错误 2.通过google查询,问题是表空间文件不够了 "表空间大小(M)",(a.bytes "已使用空间(M)&qu ...
- 七、Mosquito 集群搭建
本章主要讲述Mosquitto 集群搭建的两种方式 1.进行双服务器搭建 2.进行多服务器搭建 一.Mosquitto的分布式集群部署 如果需要做并发量很大的时候就需要考虑做集群处理,但是我在查找资料 ...
- php 通过http user-agent判断是否为手机浏览器
<?php/*** 判断是否是通过手机访问* @return bool 是否是移动设备 */public function isMobile() { //判断手机发送的客户端标志 if ...
- quick cocos2d-x 下载地址
https://github.com/chukong/quick-cocos2d-x/tree/master http://www.cocos2dx.net/post/280 配置说明 http:// ...