c# 委托

2021-07-09 10:04

阅读:697

标签: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


评论


亲,登录后才可以留言!