学习笔记:委派 和 事件(一)

    技术2022-05-11  71

    using System;

    using System.Collections.Generic;

    using System.Text;

     

    //Declare Delegate -- defines requried signature:

    //声明一个委派

    delegate void SampleDelegate(string massage);

     

    namespace DelegateConsoleApp

    {

        class Program

        {

            // Regular method that mathes signature:

            //事先声明一个委派

            static void SampleDelegateMethod(string message)

            {

                Console.Write(message);

            }

     

            static void Main(string[] args)

            {

                //Instantiate delegate with named method

                //实例化一个委派的d1,指出d1调用一个已经定义的方法

                SampleDelegate d1 = SampleDelegateMethod;

                //Instantiate delegate with anonymouns method:

                //实例化一个委派的d2,指出d2 调用一个匿名的方法。

                SampleDelegate d2 = delegate(string message)

                {

                    Console.WriteLine(message);

                    Console.WriteLine("I am Superman");

                };

     

                // Invoke delegate d1:

                d1("Hello");

                // Invoke delegate d2:

                d2(" World");

            }

        }

    }

     


    最新回复(0)