zoukankan      html  css  js  c++  java
  • 委托

    using System;
    using System.Collections.Generic;
    using System.Text;
    namespace ConsoleApplication1
    {
    class Program
    {
    static void Main(string[] args)
    {
    // 创建一个委托实例,封装C类的静态方法M1
    MyDelegate d1 = new MyDelegate(C.M1);
    d1("D1"); // M1
    // 创建一个委托实例,封装C类的静态方法M2
    MyDelegate d2 = new MyDelegate(C.M2);
    d2("D2"); // M2
    // 创建一个委托实例,封装C类的实例方法M3
    MyDelegate d3 = new MyDelegate(new C().M3);
    d3("D3"); // M3
    // 从一个委托d3创建一个委托实例
    MyDelegate d4 = new MyDelegate(d3);
    d4("D4"); // M3
    // 组合两个委托
    MyDelegate d5 = d1 + d2;
    d5 += d3;
    d5("D5"); // M1,M2,M3
    // 从组合委托中删除d3
    MyDelegate d6 = d5 - d3;
    d6("D6"); // M1,M2
    d6 -= d3; // 虽然d6调用列表中已经没有d3了,但这样只是不可能的移除没有错误发生
    d6("D6"); // M1,M2
    d6 -= d6;
    //d6("D6"); 此时d6的调用列表为空,d6为null,所以引发System.NullReferenceException
    MyDelegate d7 = new MyDelegate(C1.P1);
    d7("D7"); // C1.P1
    MyDelegate d8 = new MyDelegate(new C2().P1);
    d8("D8"); // C2.P1
    }
    }
    // 声明一个委托MyDelegate
    public delegate void MyDelegate(string str);
    public class C
    {
    public static void M1(string str)
    {
    Console.WriteLine("From:C.M1: {0}", str);
    }
    public static void M2(string str)
    {
    Console.WriteLine("From:C.M2: {0}", str);
    }
    public void M3(string str)
    {
    Console.WriteLine("From:C.M3: {0}", str);
    }
    }
    public class C1
    {
    public static void P1(string str)
    {
    Console.WriteLine("From:C1.P1: {0}", str);
    }
    }
    public class C2
    {
    public void P1(string str)
    {
    Console.WriteLine("From:C2.P1: {0}", str);
    }
    }
    }
  • 相关阅读:
    猜数小游戏
    Please change caller according to com.intellij.openapi.project.IndexNotReadyException documentation。
    Android Studio —— Executing tasks
    C语言如何输出ASCII码
    Generator
    poj1919--Red and Black (DFS)
    poj1699--Best Sequence (DFS+查表)
    poj1753-Flip Game BFS+位运算
    Zombie 僵尸感染--BFS
    Java视频
  • 原文地址:https://www.cnblogs.com/YzpJason/p/6486877.html
Copyright © 2011-2022 走看看