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);
            }
        }
    
    }
  • 相关阅读:
    CSS 实现图片灰度效果
    有关楼层滚动且对应楼层Nav导航高亮显示
    本地上传图片预览效果
    gulp.js 的安装以及使用
    ReactJS -- 初学入门
    ie8下jquery改变PNG的opacity出现黑边
    数据库操作 (4-3)
    Python之协程 (4-2)
    python 之 线程 3-29
    Python之 并发编程(3-19)
  • 原文地址:https://www.cnblogs.com/jestin/p/11543308.html
Copyright © 2011-2022 走看看