zoukankan      html  css  js  c++  java
  • 委托

    委托

    说白了 就是调用类里的方法

    方法的指针,是引用类型,这与类和接口类似

      指向的不是类,是方法

      方法的多态,同一个委托指向不同的方法

    单路广播:

    class Program
        {
            static void Main(string[] args)
            {
                //单路委托
                MathOP op = null;
                MyClass c = new MyClass();
                op = new MathOP(c.Add);
                int r = c.Add(1, 2);
                r = op(1, 2);
                Console.WriteLine(r);
                op = new MathOP(MyClass2.Sub);
                r = op(1, 2);
                Console.WriteLine(r);
                Console.ReadKey();
            }
        }
        public delegate int MathOP(int a, int b);
        //定义一种委托指针类型,可以指向特定的方法
        public class MyClass
        {
            public int Add(int x, int y)
            {
                return x + y;
            }
        }
        public class MyClass2
        {
            public static int Sub(int x, int y)
            {
                return x - y;
            }
        }
    View Code

    多路广播:

        class Program
        {
            static void Main(string[] args)
            {
                //使用多路广播 一般不推荐有返回值
                预报天气 d = null;
                var s = new 学生();
                d = new 预报天气(new 工人().看报纸上的天气);
                d += new 预报天气(s.校园广播);
                d(16);
                d -= new 预报天气(s.校园广播);//减去的方法的地址得正确
                d(16);
                Console.ReadKey();
            }
            public delegate void 预报天气(int 温度);
            public class 工人
            {
                public void 看报纸上的天气(int tmp)
                {
                    Console.WriteLine("工人得知当前温度为:{0}", tmp);
                }
            }
            public class 学生
            {
                public void 校园广播(int tmp)
                {
                    Console.WriteLine("学生得知当前温度为:{0}", tmp);
                }
            }
        }
    View Code
  • 相关阅读:
    浅谈c#中使用lock的是与非
    C#设计模式学习笔记单例模式
    ArrayList c.toArray might (incorrectly) not return Object[] (see 6260652)
    java.lang.Object 之 clone() 使用

    把以前的补齐 张
    String的方法 张
    随便写写 张
    集合框架 张
    java 张
  • 原文地址:https://www.cnblogs.com/handsomer/p/4153534.html
Copyright © 2011-2022 走看看