FUNC方差与多个参数 [英] Func variance with multiple parameters

查看:526
本文介绍了FUNC方差与多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试过在我们的代码是这样的,但它失败:

Tried to something like this in our code but it fails:

Func<Employee, Employee> _myFunc;

void Main()
{
    Func<Employee, Employee> test1  = _myFunc;//Ok
    Func<Employee, Person> test2  = _myFunc;//Ok
    Func<Person, Employee> test3 = _myFunc;//Fails
    Func<Person, Person> test4  = _myFunc;//Fails
}

public class Person { }
public class Employee : Person { }

在后两种情况给这个错误:

The last two cases give this error:

无法隐式转换类型 System.Func<员工,员工与GT; System.Func<人,员工> 。一个显式转换存在(是否缺少强制转换?)

Cannot implicitly convert type System.Func<Employee, Employee> to System.Func<Person, Employee>. An explicit conversion exists (are you missing a cast?)

任何想法,为什么?

推荐答案

如果你看一下签名 Func键< T,TResult> ,你会看到的输入参数( T 在这种情况下)是的逆变的,返回类型( TResult )是

If you look at the signature for Func<T, TResult>, you'll see that the input parameters (T in this case) are contravariant, and the return type (TResult) is covariant

public delegate TResult Func<in T, out TResult>(T arg);



逆变基本上是对能够通过一个大式的方法期待的小类型,其中协方差是完全相反的。

Contravariance is basically about being able to pass a "bigger" type to a method expecting a "smaller" type, where covariance is exactly the opposite.

埃里克利珀提出这个的精美,优雅(重点煤矿)

Eric Lippert puts this beautifully and elegantly (emphasis mine):

一个泛型类型我为(以T),如果施工参考
类型参数的保存分配兼容性的方向 。它
逆变(以T),如果它的反转分配
兼容性
的方向。而且它的不变如果它的,既不。通过这一点,我们
只是在说在一个简洁的方式,这需要一个T
和产生我是一个协变/逆变/不变投影的投影。

A generic type I is covariant (in T) if construction with reference type arguments preserves the direction of assignment compatibility. It is contravariant (in T) if it reverses the direction of assignment compatibility. And it is invariant if it does neither. And by that, we simply are saying in a concise way that the projection which takes a T and produces I is a covariant/contravariant/invariant projection.

这篇关于FUNC方差与多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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