zoukankan      html  css  js  c++  java
  • C# 委托的一些使用上的小技巧

    1、委托是一种数据类型,我们可以在任何定义类的地方定义委托,在任何声明类的地方声明委托

    2、初始化委托有两种方式,代码如下:

    (1)、像类一样初始化委托

    public delegate void SayHelloEventHandler(string _name);
    SayHelloEventHander sh = new SayHelloEventHander(ChineseSayHello);//创建了一个SayHelloEventHandler的实例,并给SayHelloEventHandler构造函数赋了初值ChineseSayHello
    private static void ChineseSayHello(string name)
    {
                
    }

    (2)、赋初值

    public delegate void SayHelloEventHandler(string _name);
    SayHelloEventHander handler;
    handler=new Program().ChineseSayHello;//通过赋初值的方式
    private void ChineseSayHello(string name)
    {
                
    }

    3、第一次初始化委托时,不能使用+=或者-=操作,只能使用2中提供的2中初始化委托的方式,否则编译其会报错。

    4、初始化化完委托之后,委托可以使用+=或者-=操作,因为一个委托可以绑定多个方法,具体是多少,每测过,你可以写个循环测下,代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Delegate
    {
        class Program
        {
            public delegate void SayHelloEventHandler(string name);
            static void Main(string[] args) {
                Program p = new Program();
                string n="张三";
                SayHelloEventHandler handler;
                handler = p.SayChHi;
                handler += p.SayChHi;
                handler += p.SayChHi;
                handler += p.SayChHi;
                handler += p.SayChHi;
                handler += p.SayChHi;
                handler += p.SayChHi;
                handler += p.SayChHi;
                p.SayHi(n, handler);
            }
            public void SayHi(string name,SayHelloEventHandler handler) {
                handler(name);
            }
            public void SayChHi(string name) {
                Console.WriteLine("你好 " + name);
                Console.ReadKey();
            }
            public void SayEnglishHi(string name) {
                Console.WriteLine("Hello " + name);
                Console.ReadKey();
            }
        }
    }

    绑定多次的结果就是执行多次绑定的方法,当前委托绑定了8个相同的方法,所以执行了8次同一个方法.

  • 相关阅读:
    How To Build CyanogenMod Android for smartphone
    CentOS安装Code::Blocks
    How to Dual boot Multiple ROMs on Your Android SmartPhone (Upto Five Roms)?
    Audacious——Linux音乐播放器
    How to Dual Boot Multiple ROMs on Your Android Phone
    Everything You Need to Know About Rooting Your Android Phone
    How to Flash a ROM to Your Android Phone
    什么是NANDroid,如何加载NANDroid备份?
    Have you considered compiled a batman-adv.ko for android?
    BATMAN—Better Approach To Mobile Adhoc Networking (B.A.T.M.A.N.)
  • 原文地址:https://www.cnblogs.com/GreenLeaves/p/6861186.html
Copyright © 2011-2022 走看看