码迷,mamicode.com
首页 > Windows程序 > 详细

c# 委托

时间:2018-09-27 10:29:35      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:move   eve   OLE   属性   string   this   col   run   private   

委托

 

public class TestprogramDelegate
    {
        public delegate void TestDelegate(string programeName);    //创建委托方法

        public TestDelegate testDelegate;       //创建委托
         
        public void run (string programerName)   //运行委托方法
        {
            testDelegate(programerName);
        }

    }

    public class ProgramTest
    {
        public void programC(string programName)
        {
            Console.WriteLine("{0}使用C语言编程", programName);
        }
        public void programJava(string programName)
        {
            Console.WriteLine("{0}使用Java语言编程", programName);
        }
        public void programCSharp(string programName)
        {
            Console.WriteLine("{0}使用CSharp语言编程", programName);
        }
        public void programPython(string programName)
        {
            Console.WriteLine("{0}使用Python语言编程", programName);
        }

        public void runDelegate()
        {
            TestprogramDelegate test1 = new TestprogramDelegate(); 

            test1.testDelegate += programCSharp;
            test1.testDelegate += programPython;   //方法绑定委托
            test1.testDelegate += programJava;

            test1.run("小兰");    //运行委托中的运行委托方法

        }
    }
programTest programTest = new programTest();
programTest.runDelegate();   //运行

 

委托+事件

运行方法同上

class programDelegateEvent
{
    public delegate void programDelegate(string programName);  //创建委托方法

    private event programDelegate myEvent;     //创建基于委托的事件字段

    public event programDelegate MyEvent    //创建时间属性
    {
        add
        {
            this.myEvent += value;    //绑定方法
        }
        remove
        {
            this.myEvent -= value;   //解绑方法
        }
    }
    public void Run(string programName)    //运行委托
    {
        myEvent(programName);
    }


}

public class programTest
{
    public void programC(string programName)
    {
        Console.WriteLine("{0}使用C语言编程", programName);
    }
    public void programJava(string programName)
    {
        Console.WriteLine("{0}使用Java语言编程", programName);
    }
    public void programCSharp(string programName)
    {
        Console.WriteLine("{0}使用CSharp语言编程", programName);
    }
    public void programPython(string programName)
    {
        Console.WriteLine("{0}使用Python语言编程", programName);
    }

    public void runDelegate()
    {
        programDelegateEvent test1 = new programDelegateEvent();   
        test1.MyEvent += programJava;
        test1.MyEvent += programC;

        test1.Run("小明");
    }
}

 

c# 委托

标签:move   eve   OLE   属性   string   this   col   run   private   

原文地址:https://www.cnblogs.com/xt112233/p/9711138.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!