zoukankan      html  css  js  c++  java
  • 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();

    }

    }

    }

    原文

  • 相关阅读:
    有return的情况下try_catch_finally的执行顺序
    java异常处理之try_catch_finally
    乔布简历
    策略模式--经典详细分析
    观察者模式(Observer Pattern)(二):HeadFirst中的气象站的实现
    luogu2444 [POI2000]病毒
    bzoj3172 luogu3966 [TJOI2013]单词
    luogu3808 luogu3796 AC自动机(简单版) AC自动机(加强版)
    vijos1459 车展
    poj2985 The k-th Largest Group
  • 原文地址:https://www.cnblogs.com/hgmyz/p/12352826.html
Copyright © 2011-2022 走看看