为什么 C# 编译器无法在指定示例中将 T 推断为 int?
void Main()
{
int a = 0;
Parse("1", x => a = x);
// Compiler error:
// Cannot convert expression type 'int' to return type 'T'
}
public void Parse<T>(string x, Func<T, T> setter)
{
var parsed = ....
setter(parsed);
}
lambda 上的方法类型推断要求拉姆达参数在类型之前就已经知道returns被推断出来。例如,如果您有:
void M<A, B, C>(A a, Func<A, B> f1, Func<B, C> f2) { }
和一个电话
M(1, a=>a.ToString(), b=>b.Length);
那么我们可以推断:
A is int, from the first argument
Therefore the second parameter is Func<int, B>.
Therefore the second argument is (int a)=>a.ToString();
Therefore B is string.
Therefore the third parameter is Func<string, C>
Therefore the third argument is (string b)=>b.Length
Therefore C is int.
And we're done.
看,我们需要 A 来算出 B,需要 B 来算出 C。在您的情况下,您想从... T 算出 T。但您不能这样做。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)