【发布时间】:2010-11-15 21:14:38
【问题描述】:
为什么 C# 编译器不能推断出 FooExt.Multiply() 满足 Functions.Apply() 的签名这一事实?我必须指定一个单独的Func<Foo,int,int> 类型的委托变量才能使代码工作......但似乎类型推断应该处理这个问题。我错了吗?如果是,为什么?
编辑:收到的编译错误是:
方法
FirstClassFunctions.Functions.Apply<T1,T2,TR>(T1, System.Func<T1,T2,TR>, T2)'的类型参数无法从用法中推断出来。尝试明确指定类型参数
namespace FirstClassFunctions {
public class Foo {
public int Value { get; set; }
public int Multiply(int j) {
return Value*j;
}
}
public static class FooExt {
public static int Multiply(Foo foo, int j) {
return foo.Multiply(j);
}
}
public static class Functions {
public static Func<TR> Apply<T1,T2,TR>( this T1 obj,
Func<T1,T2,TR> f, T2 val ) {
return () => f(obj, val);
}
}
public class Main {
public static void Run() {
var x = new Foo {Value = 10};
// the line below won't compile ...
var result = x.Apply(FooExt.Multiply, 5);
// but this will:
Func<Foo, int, int> f = FooExt.Multiply;
var result = x.Apply(f, 5);
}
}
【问题讨论】:
-
以下应该也可以工作:
x.Apply(new Func<Foo, int, int>(FooExt.Multiply), 5)。什么是编译错误? -
在 .NET 4.0 中对我来说似乎编译得很好。
-
您确定这是您使用的确切代码吗?为了我们的利益,您还没有“简化”它?
-
是的,C# 3.0 编译器不处理这个问题,4.0 编译器可以处理,即使目标是 .NET 3.5。
标签: c# .net generics c#-3.0 type-inference