Passing a Delegate Object to a Method with the Func <> Parameter

I have a Foo4 method that takes a parameter of type Func <>. If I pass a parameter of an anonymous type, I will not get an error. But if I create and pass in a delegate object that references a method with the correct signature, I get a compiler error. I can not understand why I get an error in this case.

class Learn6
    {
        delegate string Mydelegate(int a);
        public void Start()
        {
            Mydelegate objMydelegate = new Mydelegate(Foo1);

            //No Error
            Foo4(delegate(int s) { return s.ToString(); });

            //This line gives compiler error.
            Foo4(objMydelegate);

        }

        public string Foo1(int a) { return a.ToString();}



        public void Foo4(Func<int, string> F) { Console.WriteLine(F(42)); }
    }
+3
source share
4 answers

It works if you pass the method reference directly:

Foo4(Foo1);

, . , . (, ), - .

:

public class Foo
{
    public string Property {get;set;}
}

public class Bar
{
    public string Property {get;set;}
}

, "", .

+8

Func<int, string> MyDelegate - . ; .

+4
        //This line gives compiler error.
        Foo4(objMydelegate);

        //This works ok.
        Foo4(objMydelegate.Invoke);
0

, Mydelegate, Func < int, string > :)

0

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


All Articles