Alf*_*ort 7 c# generics signature void
我有一个类必须接收方法,以便调用它们以及执行其他执行.这些方法必须多次使用,并且对于许多不同的用户,因此越简单越好.
为了解决这个问题,我有两种方法:
void Receive(Action func)
{
// Do some things.
func();
}
T Receive<T>(Func<T> func)
{
// Do some things.
return func();
}
Run Code Online (Sandbox Code Playgroud)
(实际上我有34种方法可以接收任何不同的Action或Func定义.)
然后,我希望能够将任何方法作为参数传递给Receive函数,以便能够执行以下操作:
void Test()
{
Receive(A);
Receive(B);
}
void A()
{
}
int B()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
就像这样,它在Receive(B)中给出了一个错误:
The call is ambiguous between the following methods or properties: 'Class1.Receive(System.Action)' and 'Class1.Receive<int>(System.Func<int>)'
Run Code Online (Sandbox Code Playgroud)
好的,签名是相同的(虽然如果我不使用这些方法,则不会显示错误).
如果我删除Receive(Action)方法,我会收到Receive(A)以下错误:
The type arguments for method 'Class1.Receive<T>(System.Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Run Code Online (Sandbox Code Playgroud)
但是我在这种情况下的类型是无效的,禁止将它用作通用参数.
那么,有没有办法让我的Receive方法不使用任何显式的Action或Func?