我正在处理一个接受两个函数作为参数并返回一个新组合函数的函数:
public static Action<T> Compose<T>(Action<T> first, Action second)
{
return new Action<T>(arg =>
{
first(arg);
second();
});
}
我注意到,如果我将静态或成员函数(而不是实际的 Action<T>
对象)发送给编译器时不指定 T
,编译器会发出警告:
static void Main(string[] args)
{
// compiler error here
var composed = Compose(Test, () => Console.WriteLine(" world"));
composed("hello");
Console.ReadLine();
}
public static void Test(string arg)
{
Console.Write(arg);
}
错误信息:
我的问题:为什么这里不能推断类型参数?无法从使用中推断方法 'ConsoleTest.Program.Compose(System.Action, System.Action)' 的参数。请尝试明确指定类型参数。
Test
的签名在编译时已知,不是吗?难道真的有一些函数可以替代Test
,使其签名模糊不清吗?
注:我知道我可以简单地将Test
替换为new Action<string>(Test)
发送到Compose
(如此问题中所述)——我的问题是“为什么”,而不是“我该怎么做”。
Compose<string>
也可以解决这个问题。 - Austin Salonen