[C# 4.0] 5. Covariance & Contravariance
2010-09-30 21:07:01 来源:WEB开发网同样,Framework 4.0 中也为常用的泛型委托做了一些准备。
namespace System
{
// Summary:
// Encapsulates a method that has no parameters and returns a value of the type
// specified by the TResult parameter.
//
// Type parameters:
// TResult:
// The type of the return value of the method that this delegate encapsulates.This
// type parameter is covariant. That is, you can use either the type you specified
// or any type that is more derived. For more information about covariance and
// contravariance, see Covariance and Contravariance in Generics.
//
// Returns:
// The return value of the method that this delegate encapsulates.
public delegate TResult Func<out TResult>();
}
2. Contravariance
泛型逆变规则:
* 泛型参数受 in 关键字约束,只能用于属性设置或委托(方法)参数。
* 隐式转换目标的泛型参数类型必须是当前类型的 "继承类"。
in 约束示例:
interface ITest<in T>
{
T X
{
get; // Not Allowed!
set; // Allowed!
}
T M(T o); // Return Not Allowed! Parameter Allowed!
}
Tags:Covariance amp Contravariance
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接