您的位置:首页 > 其它

一个简单的Delegate使用例子

2017-02-10 13:45 531 查看
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace delegateDemo

{

    class Program

    {

        static void OtherClassMethod()

        {

            Console.WriteLine("another class's static method");

        }

        static void Main(string[] args)

        {

            var test = new TestDelegate();

            test.delegateMethod = new TestDelegate.DelegateMethod(test.NonStaticMethod);

            test.delegateMethod += new TestDelegate.DelegateMethod(TestDelegate.StaticMethod);

            test.delegateMethod += Program.OtherClassMethod;

            test.RunDelegateMethods();

        }

    }

    class TestDelegate

    {

        public delegate void DelegateMethod();  //声明了一个Delegate Type

        public DelegateMethod delegateMethod;   //声明了一个Delegate对象

        public static void StaticMethod()

        {

            Console.WriteLine("Delegate a static method");

        }

        public void NonStaticMethod()

        {

            Console.WriteLine("Delegate a non-static method");

        }

        public void RunDelegateMethods()

        {

            if (delegateMethod != null)

            {

                Console.WriteLine("---------");

                delegateMethod.Invoke();

                Console.WriteLine("---------");

            }

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: