我有这段简单的代码:
class Program
{
static void test<T1>(Action<T1> action) { }
static void test<T1, T2>(Action<T1, T2> action) { }
static void B(int a) { }
static void C(string a, int b) { }
static void Main(string[] args)
{
test(B);
test(C);
}
}
Run Code Online (Sandbox Code Playgroud)
由于两个错误而无法编译:
The type arguments for method 'Program.test<T1>(Action<T1>)' cannot be
inferred from the usage. Try specifying the type arguments explicitly.
The type arguments for method 'Program.test<T1>(Action<T1>)' cannot be
inferred from the usage. Try specifying the type arguments explicitly.
Run Code Online (Sandbox Code Playgroud)
当然,如果我明确指定类型参数,它将起作用。
test<int>(B);
或者,如果我将B强制转换为正确的Action类型:
test((Action<int>) B)
Run Code Online (Sandbox Code Playgroud)
我希望有一个优雅的解决方案,其中C#编译器会自动识别正确的方法重载。
这是唯一可能吗?