一个关于委托的小例子

public delegate int MyDel2(int i, string s);
        public delegate void MyDel(int n);
        public delegate string HahaDelegate();
        static void Main(string[] args)
        {
            //MyDel d1 = new MyDel(M1);//声明一个MyDel类型的变量d1,并声明民为MyDel类型的变量d1, new  MyDel(M1)创建一个指向M1方法的委托。
            //d1(5);//调用d1指向的方法。

            MyDel2 d2 = new MyDel2(M3);
            int d2Result = d2(888, "aaa");
            Console.WriteLine(d2Result);


            //HahaDelegate d1 = new HahaDelegate(Haha);
            //Console.WriteLine(d1);
            //Console.WriteLine(d1());//区分加括号和不加括号的区别

            //d1 = new HahaDelegate(Haha2);
            //Console.WriteLine(d1());

            //HahaDelegate d1 = Haha;
            //Console.WriteLine(d1());

            //MyDel d1 = M1;//MyDel d1 = M1();不能加括号,加括号返回方法,不加指向这个方法
            //Console.WriteLine(d1);

            Console.ReadKey();
        }
        static string Haha()
        {
            return "1111";
        }

        static string Haha2()
        {
            return "2222";
        }
        static void M1(int a)
        {
            Console.WriteLine("M1" + a);
        }
        static int M2(string a)
        {
            return 5;
        }
        static int M3(int i, string str)
        {
            return i + 5;
        }
    }
    delegate void MyDel1(string s, string s1);
发布了103 篇原创文章 · 获赞 40 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/chenguanghan123/article/details/89400433