开发者

C# Polymorphysm: overloading function, accepting delegates Action<T> and Func<T,R>?

Here's a simple code, where I try to implement some sort of polymorphysm.

You can see overloaded Invoker function, accepting Func<T,R> and Action<T> as an argument.

Compiler says it couldn't be compiled because of ambiguity if Invoker methods:

class Program
{
    static void Invoker(Action<XDocument> parser)
    {
    }

    static void Invoker(Func<XDocument,string> parser)
    {
    }

    static void Main(string[] args)
    {
        Invoker(Action);
        Invoker(Function);
    }

    static void Action(XDocument x)
    {
    }

    static string Function(XDocument x)
    {
        return "";
    }
}

I get 3(!) errors, and none of it i can explain. Here they are:

Error 1 The call is ambiguous between the following methods or properties: 'ConsoleApplication3.Program.Invoker(System.Action)' and 'ConsoleApplication3.Program.Invoker(System.Func)' c:\users\i.smagin\documents\visual studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs 21 4 ConsoleApplication3

Error 2 The call is ambiguous between the following methods or properties: 'ConsoleApplication3.Program.Invoker(System.Action)' and 'ConsoleApplication3.Program.Invoker(System.Func)' c:\users\i.smagin\documents\visual studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs 22 4 ConsoleApplication3

Error 3 'string ConsoleApplication3.Program.Function(System.Xml.Linq.XDocument)' has the wr开发者_JAVA技巧ong return type c:\users\i.smagin\documents\visual studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs 22 12 ConsoleApplication3

Any ideas?


Both

static void Action(XDocument x)

and

static string Function(XDocument x)

have same method signature.

Return value is not part of method signature. So, just having a different return type won't work. They must have different number of parameters or parameter types must be different.

Since, compiler cannot figure out which one (method that takes Action or method that takes Func) to use, you have to explicitly specify it:

Invoker(new Action<XDocument>(Action));
Invoker(new Func<XDocument, String>(Function));

to resolve ambiguity.


You can invoke your methods like that:

public static void Main(string[] args)
 {
     Invoker(new Action<XDocument>(Action));
     Invoker(new Func<XDocument, string> (Function));
}

Simply, you have to tell compiler what method you want to invoke.


Slightly more elegant solution using linq:

 public static void Main(string[] args)
 {
     Invoker((xdocument)=>doSomething);      // calls action invoker
     Invoker((xdocument)=>{return doSomething;}); // calls function invoker
}

At the end of it... comes down to signatures.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜