C#委托示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExDelegate
{
    delegate void PrintFunction();
    delegate void MyDel(ref int x);
    class Test
    {
        public void print1()
        {
            Console.WriteLine("Print1---instance");
        }
        public static void print2()
        {
            Console.WriteLine("Print2---static");
        }
    }
    class MyClass
    {
        public void Add2(ref int x)
        {
            x += 2;
        }
        public void Add3(ref int x)
        {
            x += 3;
        }
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
            MyDel md = mc.Add2;
            md += mc.Add3;
            int x = 5;
            md(ref x);
            Console.WriteLine("Value:{0}",x);
            Test t1 = new Test();
            PrintFunction pf;
            pf = t1.print1;
            pf += Test.print2;
            if (null != pf)
            {
                pf();
            }
            else
            {
                Console.WriteLine("Delegate is empty");
            }
            Console.ReadKey();
        }
    }
}
原文地址:https://www.cnblogs.com/sulong/p/4797756.html