欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#委托把方法当成参数(实例讲解)

程序员文章站 2024-02-13 21:28:34
静态方法代理:复制代码 代码如下:public delegate void dogreeting(string name); class program &n...

静态方法代理:

复制代码 代码如下:

public delegate void dogreeting(string name);

class program
    {
        [stathread]
        static void main(string[] args)
        {
            //方法名当成参数传给委托类型调用
            markgreeting("张三", greetingenglish);
            markgreeting("李四", greetingchinese);
        }

        /// <summary>
        /// 委托(代理的方法)
        /// </summary>
        /// <param name="name"></param>
        /// <param name="markgreeting"></param>
        private static void markgreeting(string name, dogreeting markgreeting)
        {
            markgreeting(name);
        }

        /// <summary>
        /// 用英文打招呼
        /// </summary>
        /// <param name="name"></param>
        private static void greetingenglish(string name)
        {
           console.writeline(name+"hello!");
        }

        /// <summary>
        /// 用中文打招呼
        /// </summary>
        /// <param name="name"></param>
        private static void greetingchinese(string name)
        {
            console.writeline(name+"你好!");
        }
    }


实例方法代理:
复制代码 代码如下:

 public delegate void dogreeting(string name);

    public class greeting
    {
        /// <summary>
        /// 委托(代理的方法)
        /// </summary>
        /// <param name="name"></param>
        /// <param name="markgreeting"></param>
        public void markgreeting(string name, dogreeting markgreeting)
        {
            markgreeting(name);
        }

        /// <summary>
        /// 用英文打招呼
        /// </summary>
        /// <param name="name"></param>
        public  void greetingenglish(string name)
        {
            console.writeline(name + "hello!");
        }

        /// <summary>
        /// 用中文打招呼
        /// </summary>
        /// <param name="name"></param>
        public void greetingchinese(string name)
        {
            console.writeline(name + "你好!");
        }
    }

    class program
    {
        [stathread]
        static void main(string[] args)
        {
            greeting greetingobj = new greeting();

            greetingobj.markgreeting("张三", greetingobj.greetingenglish);
            greetingobj.markgreeting("李四", greetingobj.greetingchinese);

        }