C#的委托

来源:互联网 发布:countdown.js中文文档 编辑:程序博客网 时间:2024/05/21 10:33

想要在恰当的时间执行一系列操作。如果代码想要执行操作,但不知道操作细节,一般可以使用委托。

让委托执行四步:

1.     声明委托类型;

2.     必须有一个方法包含了要执行的代码;

3.     必须创建一个委托实例;

4.     必须调用委托实例。


using System;


namespace ConsoleDemo2
{
    public delegate void GreetingDelegate(string name);
    class Program
    {
        private static void EnglishGreeting(string name)
        {
            Console.WriteLine("Morning," + name);
        }


        private static void ChineseGreeting(string name)
        {
            Console.WriteLine("早上好," + name);
        }


        private static void GreetPeople(string name, GreetingDelegate MakeGreeting)
        {
            MakeGreeting(name);
        }
        static void Main(string[] args)
        {
            GreetPeople("KYO", EnglishGreeting);
            GreetPeople("大王", ChineseGreeting);
            Console.ReadKey();
        }
    }
}

0 0
原创粉丝点击