C # Polymorphism: overload function, accepting delegates Action <T> and Func <T, R>?

Here is a simple code where I am trying to implement some kind of polymorphism.

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

The compiler says that it cannot be compiled due to ambiguity if the 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 this can I explain. Here they are:

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

2 : 'ConsoleApplication3.Program.Invoker(System.ction)' 'ConsoleApplication3.Program.Invoker(System.Func)' c:\users\i.smagin\documents\visual studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs 22 4 ConsoleApplication3

3 ' ConsoleApplication3.Program.Function(System.Xml.Linq.XDocument)' c:\users\i.smagin\documents\visual studio 2010\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs 22 12 ConsoleApplication3

?

+3
3

static void Action(XDocument x)

static string Function(XDocument x)

​​ .

. , . , .

, (, Action , Func) , :

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

.

+6

:

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

, .

+4

A 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 this ... comes down to signatures.

+3
source

Source: https://habr.com/ru/post/1791203/


All Articles