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背景颜色渐变效果
    manachar算法小结
    hdu--3068 最长回文串(manachar模板)
    ac自动机小结
    hdu--2896 病毒侵袭(ac自动机)
    hdu--1251 统计难题(字典树水题)
    hdu--1540 Tunnel Warfare(线段树+区间合并)
    poj--3667 Hotel(线段树+区间合并)
    hdu--3308 LCIS(线段树+区间合并)
    hdu--5023 A Corrupt Mayor's Performance Art(线段树+区间更新+位运算)
  • 原文地址:https://www.cnblogs.com/jestin/p/11543308.html
Copyright © 2011-2022 走看看