Cast delegate to Func in C#

后端 未结 8 2088
小蘑菇
小蘑菇 2020-12-01 12:03

I have code:

public delegate int SomeDelegate(int p);

public static int Inc(int p) {
    return p + 1;
}

I can cast Inc to

8条回答
  •  醉话见心
    2020-12-01 12:13

    I like examples. Here is my example code:

    class Program
    {
        class A
        {
            public A(D d) { d.Invoke("I'm A!"); }
            public delegate string D(string s);
        }
    
        class B
        {
            public delegate string D(string s);
        }
        static void Main(string[] args)
        {
            //1. Func to delegates 
    
            string F(dynamic s) { Console.WriteLine(s); return s; }
            Func f = F;
            //new A(f);//Error CS1503  Argument 1: cannot convert from 'System.Func' to 'ConsoleApp3.Program.A.D'  
            new A(new A.D(f));//I'm A!
            new A(x=>f(x));//I'm A!
    
            Func f2 = s => { Console.WriteLine(s); return s; };
            //new A(f2);//Same as A(f)
            new A(new A.D(f2));//I'm A!
            new A(x => f2(x));//I'm A!
    
            //You can even convert between delegate types
            new A(new A.D(new B.D(f)));//I'm A!
    
    
    
            //2. delegate to F
    
            A.D d = s => { Console.WriteLine(s); return s; };
    
            Func f3 = d.Invoke;
            f3("I'm f3!");//I'm f3!
            Func f4 = new Func(d);
            f4("I'm f4!");//I'm f4!
    
    
            Console.ReadLine();
        }
    }
    

    The output is:

提交回复
热议问题