C# 委托的理解

1、什么是委托

委托可以理解为持有一个或多个方法的对象。如果执行委托的话,委托会

执行它所"持有"的方法。委托可以避免程序中大量使用if-else语句,使

程序拥有更好的扩展性。

2、委托的本质

委托和类一样,是一种用户自定义的类型,但类表示的是数据和方法的集合,

而委托则持有一个或多个方法,以及一系列预定义的操作。

3、如何声明委托

delegate void MyDel(int x)

说明:delegate 作为委托关键字,没有方法主体

4、什么是多播委托?

可以把多个方法赋值给同一个委托,或者将多个方法绑定到同一个委托,

就是多播委托。

5、一个简单的委托demo:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace SimpleDelegateDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            Class1 c2 = new Class1();

            c2.MethodUseDelegate();     //调用方法

        }

    }

    class Class1

    {

        public  delegate void SimpleDelegate();      //定义一个委托

        SimpleDelegate delegateMethod = UseMethod;   //将方法传递给定义的另一个方法(委托)

        public void MethodUseDelegate()

        {

            Class1 c1 = new Class1();

            c1.delegateMethod();                    //将传递赋值的委托当做方法调用

//SimpleDelegate+=c1.UseMethod2 //绑定第二个方法

//SimpleDelegate-=c1.UseMethod2 //移除第二个方法

        }        

        public static void UseMethod()

        {

            Console.WriteLine("一个简单委托列子");

            Console.ReadKey();

        }

        public static void UseMethod2()

        {

            Console.WriteLine("一个简单委托列子2");

            Console.ReadKey();

        } 

    }

}

 

 我的公众号开通了 欢迎关注 

posted @ 2017-06-07 12:46  天使不哭  阅读(899)  评论(0编辑  收藏  举报