简体   繁体   English

从Func <object,string>到Func <string,string>的转换工作但到Func <int,string>失败

[英]Conversion from Func<object,string> to Func<string,string> works but to Func<int,string> fails

I have the following code: 我有以下代码:

static Func<object, string> s_objToString = (x) => x.ToString();
static Func<string, string> s_stringToString = s_objToString; //compiles
static Func<int, string> s_intToString = s_objToString; //error

The second line compiles but the third line fails to compile with error: 第二行编译但第三行无法编译并出现错误:

Cannot implicitly convert type ' System.Func<object,string> ' to ' System.Func<int,string> ' 无法将类型' System.Func<object,string> '隐式转换为' System.Func<int,string> '

Why is that? 这是为什么?

I understand that with genetics although string is derived from object a List<string> does not derive from List<object> , but here object to string works and object to int fails, why? 我理解,虽然字符串是从对象派生的,但是List<string>并不是从List<object>派生的,但是这里objectstring工作而objectint失败,为什么呢?

OK let's say I understood why; 好吧,让我说我理解为什么; the question now is there a way around it (other then defining MyInt class to box int because Func<object,string> to Func<MyInt,string> works)? 现在的问题是有一种解决方法(其他然后将MyInt类定义为box int因为Func<object,string>Func<MyInt,string>工作)?

It is because Func is defined as Func<in T, out TResult> , MSDN is here , so T is contra-variant with in keyword, that is, you can use either the type you specified or any type that is less derived, but remember that co-variance and contra-variance do not support for value type : 这是因为Func被定义为Func<in T, out TResult> ,MSDN就在这里 ,所以T是with -variant with in keyword,也就是说,你可以使用你指定的类型或任何派生类型较少的类型,但是请记住, 协方差和反方差不支持值类型

Why covariance and contravariance do not support value type 为什么协方差和逆变不支持值类型

So, it works for string but does not work out with int . 因此,它适用于string但不适用于int You might need to read more about covariance and contravariance : 您可能需要阅读有关协方差和逆变的更多信息:

http://msdn.microsoft.com/en-us/library/dd233060.aspx http://msdn.microsoft.com/en-us/library/dd233060.aspx

http://msdn.microsoft.com/en-us/library/dd799517.aspx http://msdn.microsoft.com/en-us/library/dd799517.aspx

Because co/contra-variance doesn't work for value types. 因为co / contra-variance对值类型不起作用。

Please take a look here 请看看这里

Variance is supported only if a type parameter is a reference type. 仅当类型参数是引用类型时才支持差异。 Variance is not supported for value types. 值类型不支持差异。
The following doesn't compile either: 以下内容无法编译:

// int is a value type, so the code doesn't compile.
IEnumerable<Object> objects = new List<int>(); // Compiler error here.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM