<分区>
我正在使用一个函数,该函数将两个函数作为参数,并返回一个新的组合函数:
public static Action<T> Compose<T>(Action<T> first, Action second)
{
return new Action<T>(arg =>
{
first(arg);
second();
});
}
我注意到如果我不指定 T
编译器会报错,当向它发送静态或成员函数(而不是实际的 Action<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);
}
错误信息:
The arguments for method 'ConsoleTest.Program.Compose(System.Action, System.Action)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
我的问题:为什么不能在这里推断类型参数? Test
的签名在编译时是已知的,不是吗?真的有一些功能可以代替 Test
吗? , 这会导致其签名不明确吗?
脚注:我知道我可以简单地发送 new Action<string>(Test)
而不是 Test
至 Compose
(如 this question 中所述)——我的问题是“为什么”,而不是“我该怎么做”。