[C# 4.0] 5. Covariance & Contravariance
2010-09-30 21:07:01 来源:WEB开发网逆变初看上去有些别扭。因为我们试图将 "基类" 隐式转换为 "继承类"。泛型逆变主要是为泛型委托准备的,我们看一个例子就明白了。
class Base { }
class Derived : Base { }
class Program
{
static void Main(string[] args)
{
Action<Base> _base = (o) => Console.WriteLine(o);
Action<Derived> _derived = _base;
_derived(new Derived());
}
}
逆变将 Action<Base> 隐式转换为 Action<Derived>,这正好和协变相反,从泛型参数 "继承关系" 上来说这有点不可理解。但当我们调用转换后的方法 "_derived(derivedObj)" 时会发现所提供的方法参数总是原方法的 "继承类",因此这种调用总是符合规则的。回忆一下 C# 2.0/3.0 中有关委托逆变的定义,其实是完全一致的。
namespace System
{
// Summary:
// Encapsulates a method that has a single parameter and does not return a value.
//
// Parameters:
// obj:
// The parameter of the method that this delegate encapsulates.
//
// Type parameters:
// T:
// The type of the parameter of the method that this delegate encapsulates.This
// type parameter is contravariant. That is, you can use either the type you
// specified or any type that is less derived. For more information about covariance
// and contravariance, see Covariance and Contravariance in Generics.
public delegate void Action<in T>(T obj);
}
Tags:Covariance amp Contravariance
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接