xiacy

导航

2.1.1 以各种简单的方式调用委托

    delegate void StringProcessor(string input);
    class Person
    {
        string name;
        public Person(string name) { this.name = name; }

        public void Say(string message)
        {
            Console.WriteLine("{0} Say: {1}", name, message);
        }
    }

    class Background
    {
        public static void Note(string note)
        {
            Console.WriteLine("({0})", note);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person jon = new Person("Jon");
            Person tom = new Person("Tom");
            StringProcessor jonsVoice;
            StringProcessor tomsVoice;
            StringProcessor background;

            jonsVoice = new StringProcessor(jon.Say);
            tomsVoice = new StringProcessor(tom.Say);
            background = new StringProcessor(Background.Note);

            jonsVoice("Hello,son.");
            tomsVoice.Invoke("Hello,Daddy!");
            background("An airplane flies past.");
        }
    }

 

posted on 2012-04-25 23:36  xiacy  阅读(130)  评论(0编辑  收藏  举报