Covariance and Contravariance (C#)

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

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 type IEnumerable<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 type IEnumerable<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 type IEnumerable<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#)的更多相关文章

  1. 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 ...

  2. 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 ...

  3. 协变(covariance),逆变(contravariance)与不变(invariance)

    协变,逆变与不变 能在使用父类型的场景中改用子类型的被称为协变. 能在使用子类型的场景中改用父类型的被称为逆变. 不能做到以上两点的被称为不变. 以上的场景通常包括数组,继承和泛型. 协变逆变与泛型( ...

  4. C#(转自wiki)

    C#是微软推出的一种基于.NET框架的.面向对象的高级编程语言.C#的发音为"C sharp",模仿音乐上的音名"C♯"(C调升),是C语言的升级的意思.其正确 ...

  5. C#的变迁史 - C# 4.0篇

    C# 4.0 (.NET 4.0, VS2010) 第四代C#借鉴了动态语言的特性,搞出了动态语言运行时,真的是全面向“高大上”靠齐啊. 1. DLR动态语言运行时 C#作为静态语言,它需要编译以后运 ...

  6. Adaptive Code Via C#读书笔记

    原书链接: http://www.amazon.com/Adaptive-Code-via-principles-Developer-ebook/dp/B00OCLLYTY/ref=dp_kinw_s ...

  7. Nemerle Quick Guide

    This is a quick guide covering nearly all of Nemerle's features. It should be especially useful to a ...

  8. [你必须知道的.NET]第三十一回,深入.NET 4.0之,从“新”展望

    发布日期:2009.05.22 作者:Anytao © 2009 Anytao.com ,Anytao原创作品,转贴请注明作者和出处. /// <summary> /// 本文开始,将以& ...

  9. 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 ...

随机推荐

  1. ZOJ3690—Choosing number

    题目链接:https://vjudge.net/problem/ZOJ-3690 题目意思: 有n个人,每个人可以从m个数中选取其中的一个数,而且如果两个相邻的数相同,则这个数大于等于k,问这样的数一 ...

  2. iOS 10 获取相册相机权限

            AVAudioSession *audioSession = [[AVAudioSession alloc]init]; [audioSession requestRecordPerm ...

  3. 浅析pc机上如何将vmlinuz-2.6.31-14-generic解压出vmlinux

    浅析pc机上如何将vmlinuz-2.6.31-14-generic解压出vmlinux luther@gliethttp:~$ vim /boot/grub/grub.cfg 可以看到我们进入的系统 ...

  4. Mysql中字段类型之时间戳大坑

         一 .环境说明: 在目前项目中,有这样的一张表,用来记录会议的相关信息,例如:会议的内容.会议的参会人员.会议的地点.会议的状态(会议是否已结束.会议是否被撤销).会议的开始时间以及该条信息 ...

  5. puma 配置,启动脚本

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/menxu_work/article/details/24547923 配置: puma_server ...

  6. CentOS6.5之Zabbix3.2.2 Server安装、汉化及Agent安装

    1.安装MySQL 1.1.安装MySQL rpm -ivh http://dev.mysql.com/get/mysql-community-release-el6-5.noarch.rpm yum ...

  7. HDFS集中式的缓存管理原理与代码剖析

    转载自:http://www.infoq.com/cn/articles/hdfs-centralized-cache/ HDFS集中式的缓存管理原理与代码剖析 Hadoop 2.3.0已经发布了,其 ...

  8. MongoDB的安全校验

    一.MongoDB安全校验的重要性 每个MongoDB实例中的数据库都可以有许多用户.如果没有开启安全校验,限制用户权限,则每个进到数据库的用户都能任意的对数据库数据进行读,写甚至是读写操作.这样的场 ...

  9. 使用jQuery创建节点、将节点插入到指定的位置

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...

  10. docker——数据管理

    生产环境中使用docker的过程中,往往需要对数据进行持久化,或者需要在多个容器之间进行数据共享.容器中管理数据主要有两种方式: 数据卷(Date Volumes):容器内数据直接映射到本地环境 数据 ...