我有以下代码:
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
第二行编译通过,第三行编译失败,报错:
Cannot implicitly convert type '
System.Func<object,string>
' to 'System.Func<int,string>
'
这是为什么?
据我了解,尽管字符串是从对象 a List<string>
派生的,但通过遗传学不源自 List<object>
, 但在这里 object
至 string
作品和object
至 int
失败,为什么?
好吧,假设我明白为什么;现在的问题是有办法解决它(除了将 MyInt
类定义为框 int
因为 Func<object,string>
到 Func<MyInt,string>
有效)?
最佳答案
是因为Func
定义为 Func<in T, out TResult>
, MSDN 是 here , 所以 T
与 in
是反变关键字,也就是说,您可以使用您指定的类型或派生程度较低的任何类型,但请记住协方差和逆方差不支持值类型:
Why covariance and contravariance do not support value type
因此,它适用于 string
但不适用于 int
.您可能需要阅读有关协变和逆变的更多信息:
关于c# - 从 Func<object,string> 到 Func<string,string> 的转换有效,但到 Func<int,string> 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13025176/