lep*_*pie 9 c# generics type-inference
为什么以下无法推断R:
static R Foo<R>(Func<Action<R>, R> call) { ... }
Run Code Online (Sandbox Code Playgroud)
虽然几乎是'相同',但作品:
static R Foo<R>(Func<Action, R> call) { ... }
Run Code Online (Sandbox Code Playgroud)
用法:
var i = Foo(ec => -1);
Run Code Online (Sandbox Code Playgroud)
第一个样本'必须'被编译的方式:
var i = Foo<int>(ec => -1);
Run Code Online (Sandbox Code Playgroud)
- 要么 -
var i = Foo((Action<int> ec) => -1);
Run Code Online (Sandbox Code Playgroud)
思考:从第二个片段可以看出,R已经由'lambda'的返回类型决定.为什么不能同样适用于第一个?即使使用ec(应该是另一个编译器提示),它也无法推断.
我认为问题不在于编译器无法推断出R该函数CallWithEscapeContinuation,而在于它无法推断出 lambda 的类型:
ec =>
{
Enumerable.Range(0, 100).Select(x =>
{
// Called here, the compiler has no idea what signature to expect for `ec`
// Could be Action<Int>, could be Action<Decimal> (for example).
if (x == 40) ec(x);
return x;
}).ToList();
return -1;
}
Run Code Online (Sandbox Code Playgroud)
而当您提供int提示时,它可以从 lambda 的类型和 的签名中推断出 lambda 的类型CallWithEscapeContinuation。
当您只有Action(与 相对Action<R>)时,上述内容无关紧要,因为没有类型参数影响 lambda 的可能签名。
| 归档时间: |
|
| 查看次数: |
196 次 |
| 最近记录: |