C#泛型委托类型推断 [英] C# generic delegate type inference
本文介绍了C#泛型委托类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么C#编译器在指定的示例中不能将T推断为int?
Why can't the C# compiler infer T to int in the specified example?
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要求在推测出返回的类型之前,已经知道 lambda参数的类型。因此,例如,如果您有:
Method type inference on a lambda requires that the types of the lambda parameters be already known before the types of the returns are inferred. So for example if you had:
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,而你不能这样做。
See, we need A to work out B, and B to work out C. In your case you want to work out T from... T. And you can't do that.
这篇关于C#泛型委托类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文