且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#泛型委托类型推断

更新时间:2023-10-01 14:25:28

方法类型推理在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.