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

跟風遠走 提交于 2019-12-01 18:43:16
cuongle

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

Because co/contra-variance doesn't work for value types.

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!