zoukankan      html  css  js  c++  java
  • c#委托

    delegate委托是存有对某个方法引用的一种引用类型变量。引用可在运行时被改变

    什么情况下使用委托

      a)当使用时间触发模式时

      b)  当需要封装静态方法时

      c)当调用方不需要访问实现该方法对象的其它属性,方法或接口时

      d)当需要方便的组合时

      e)当类可能需要该方法的多个实现时

    using System;
    
    namespace 编码练习
    {
        public enum Greeting
        {
            Hello, Goodbye
        }
        class Program
        {
            public static void Hello(string s)
            {
                Console.WriteLine("  Hello, {0}!", s);
                // do something (hug or shake hand...)
            }
            public static void Goodbye(string s)
            {
                Console.WriteLine("  Goodbye, {0}!", s);
                // do something (hug or wave hand...)
            }
            static void MakeGreeting(string name, Greeting greeting)
            {
                switch (greeting)
                {
                    case Greeting.Hello: Hello(name); break;
                    case Greeting.Goodbye: Goodbye(name); break;
                }
            }
            static void Main(string[] args)
            {
                MakeGreeting("May", Greeting.Hello);
                MakeGreeting("April", Greeting.Goodbye);
            }
        }
    
    
    }
    using System;
    using System.Collections.Generic;
    
    namespace 编码练习
    {
        //使用委托后的代码
        delegate void GreetingDelegate(string s); //声明委托,定义Greeting方法的类
        class Program
        {
            public static void Hello(string s)
            {
                Console.WriteLine("  Hello, {0}!", s);
                // do something (hug or shake hand...)
            }
            public static void Goodbye(string s)
            {
                Console.WriteLine("  Goodbye, {0}!", s);
                // do something (hug or wave hand...)
            }
            static void MakeGreeting(string name, GreetingDelegate d)
            {
                d(name);
            }
            static void Main(string[] args)
            {
                GreetingDelegate d1 = Hello; //定义委托的一个对象(将方法绑定到委托)
                GreetingDelegate d2 = Goodbye; //定义委托的另一个对象
                MakeGreeting("May", d1);
                MakeGreeting("April", d2);
            }
        }
    
    }
  • 相关阅读:
    自学Linux命令的四种方法
    POJ 1170 Shopping Offers -- 动态规划(虐心的六重循环啊!!!)
    九度OJ 1447 最短路 1008 最短路径问题
    九度OJ 1024 畅通工程 -- 并查集、贪心算法(最小生成树)
    PHPActiveRecord 学习三
    PHPUnit 组织测试
    PHPActiveRecord validates
    PHPActiveRecord 学习二
    PHPActiveRecord 学习一
    PHP ActiveRecord demo栗子中 关于类名 的问题
  • 原文地址:https://www.cnblogs.com/jestin/p/11543308.html
Copyright © 2011-2022 走看看