C# delegate

1. delegate

example1

class Program
{
        public delegate int MyDelegate(int i);

        int MyFunc(int i)
        {
            return i;
        }

        public void Foo()
        {
            MyDelegate f = MyFunc;
      
            Console.WriteLine(f(2));
            Console.ReadKey();
        }
}

example 2

// declare the delegate type
    public delegate string MyDelegate(int arg1, int arg2);


    class Program
    {
        // INSERT DELEGATES HERE
        static string func1(int a, int b)
        {
            return (a + b).ToString();
        }
        static string func2(int a, int b)
        {
            return (a * b).ToString();
        }

        static void Main(string[] args)
        {
            MyDelegate f = func1;
            Console.WriteLine("The number is: " + f(10, 20));
            f = func2;
            Console.WriteLine("The number is: " + f(10, 20));

            Console.WriteLine("
Press Enter Key to Continue...");
            Console.ReadLine();
        }
    }

 2. anonymous delegate

 public delegate string MyDelegate(int arg1, int arg2);

    class Program
    {
        static void Main(string[] args)
        {
            // SNIPPET GOES HERE
            MyDelegate f = delegate(int arg1, int arg2)
            {
                return (arg1 + arg2).ToString();
            };
            Console.WriteLine("The number is: " + f(10, 20));
            // Keep the console window open until a key is pressed
            Console.WriteLine("
Press Enter Key to Continue...");
            Console.ReadLine();
        }
    }

 3. composable delegate (call multiple delegates with one function call)

 // declare the delegate type
    public delegate void MyDelegate(int arg1, int arg2);

    class Program
    {
        static void func1(int arg1, int arg2)
        {
            string result = (arg1 + arg2).ToString();
            Console.WriteLine("The number is: " + result);
        }
        static void func2(int arg1, int arg2)
        {
            string result = (arg1 * arg2).ToString();
            Console.WriteLine("The number is: " + result);
        }
        static void Main(string[] args)
        {
            MyDelegate f1 = func1;
            MyDelegate f2 = func2;
            MyDelegate f1f2 = f1 + f2;

            // call each delegate and then the chain
            Console.WriteLine("Calling the first delegate");
            f1(10, 20);
            Console.WriteLine("Calling the second delegate");
            f2(10, 20);
            Console.WriteLine("
Calling the chained delegates");
            f1f2(10, 20);

            // subtract off one of the delegates
            Console.WriteLine("
Calling the unchained delegates");
            f1f2 -= f1;
            f1f2(20, 20);


            Console.WriteLine("
Press Enter Key to Continue...");
            Console.ReadLine();
        }
    }
原文地址:https://www.cnblogs.com/phoenix13suns/p/5147097.html