class Program
{
public delegate void VoidMethodDelegate();
public delegate int IntMethodDelegate();
static void Main(string[] args)
{
Test(IntMethod);
Test(VoidMethod);
}
static int IntMethod()
{
return 1;
}
static void VoidMethod()
{
}
static void Test(VoidMethodDelegate method)
{
}
static void Test(IntMethodDelegate method)
{
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试设置一个重载方法,它将采用两种不同类型的委托.代表只有返回类型不同 - 在这两种情况下它们都不带输入参数.因此,在上面的示例中,我希望能够调用Test()并将其传递给返回void的方法或返回int的方法.当我编译上面的代码时,我得到这些错误:
错误CS0121:以下方法或属性之间的调用不明确:'ConsoleApplication1.Program.Test(ConsoleApplication1.Program.VoidMethodDelegate)'和'ConsoleApplication1.Program.Test(ConsoleApplication1.Program.IntMethodDelegate)'
错误CS0407:'int ConsoleApplication1.Program.IntMethod()'具有错误的返回类型
错误CS0121:以下方法或属性之间的调用不明确:'ConsoleApplication1.Program.Test(ConsoleApplication1.Program.VoidMethodDelegate)'和'ConsoleApplication1.Program.Test(ConsoleApplication1.Program.IntMethodDelegate)'
我知道如果我使用new创建委托而不是直接传递方法,我可以解决错误,如下所示:
static void Main(string[] args)
{
Test(new IntMethodDelegate(IntMethod));
Test(new VoidMethodDelegate(VoidMethod));
}
Run Code Online (Sandbox Code Playgroud)
但是这种语法很混乱,我宁愿能够直接传递方法,而不必将其包装在对new的调用中.我见过的唯一解决方案是摆脱Test()的重载版本,而是使用两种不同的方法,每种方法都有不同的名称.
任何人都可以告诉我为什么编译器抱怨这是不明确的?我不明白为什么编译器无法决定使用哪两个重载.
c# ×1