从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

查看:354
本文介绍了从Func转换< object,string>到Func< string,string>但是对于Func< int,string>失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  static Func< object,string> s_objToString =(x)=> x.ToString(); 
static Func< string,string> s_stringToString = s_objToString; //编译
static Func< int,string> s_intToString = s_objToString; //错误

第二行编译但第三行无法编译时出错:



lockquote

不能隐式地将类型' System.Func< object,string> '转换为' System.Func< int,string> '


为什么? / strong>



据我所知,虽然字符串是从对象派生而来的,但是

List< string> 从 List< object> ,但这里 object string 工程和对象 int 失败,为什么?

好吧,让我们说我明白了为什么;现在的问题是有办法绕过它(除了定义 MyInt 类到 int ,因为 Func< object,string> to Func< MyInt,string> works)?

Func 被定义为 Func ,MSDN是此处,所以 T 是与关键字中的 contra-variant ,也就是说,您可以使用您指定的类型或任何请注意协变量和反变量不支持值类型



为什么协变和逆变不支持值类型



因此,它适用于字符串,但不适用于 INT 。您可能需要详细了解协变和逆变

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



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


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>'

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?

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)?

解决方案

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:

Why covariance and contravariance do not support value type

So, it works for string but does not work out with 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/dd799517.aspx

这篇关于从Func转换&lt; object,string&gt;到Func&lt; string,string&gt;但是对于Func&lt; int,string&gt;失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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