zoukankan      html  css  js  c++  java
  • C# 编程数据结构学习笔记 3

    1<多播委托>:

        通过一个委托调用多个方法的委托

        多播委托如果调用的结果为null的时候,这个迭代就会结束,所以多播委托的调用的方法一般为void。

    代码如下:

    namespace 多播委托
    {
    class MainClass
    {
    static void Test1()
    {
    Console.WriteLine ("test1");
    }

    static void Test2()
    {
    Console.WriteLine ("test2");
    }
    public static void Main (string[] args)
    {
    Action a = Test1;
    a += Test2;
    a ();
    Console.ReadLine ();
    }
    }
    }

    2<匿名方法>

        其实是一个方法但是就是没有名字,由委托调用

    class MainClass
    {
    static int Test(int b,int c)
    {
    return b + c;
    }

    public static void Main (string[] args)
    {
    Func<int,int,int> a = delegate(int b,int c)
    {
    return b+c;
    };
    int d = a (2, 3);
    Console.WriteLine (d);
    Console.ReadLine ();
    }
    }

    3《Lambda表达式》

      lambda表达式是用来代替匿名方法,所以它也是定义了一个方法

      lambda表达式是一种更加简洁的方法不用声明参数类型和写delegate

    代码如下:

      

    class MainClass
    {

    public static void Main (string[] args)
    {
    Func<int,int,int> a = (b,c)=>
    {
    return b+c;
    };

    }
    }

    4<事件>

       事件就是一个类或者对象向其他类或者对象通知事件的一种特殊的签名委托

    定义的规则:

      public event 委托类型 事件名;

      关键字是 event 返回的是一个委托类型

      通常的事件名的命名格式是 字符+Event来申明事件的 

      

    代码如下:

    class MainClass
    {

    public delegate void MyDelegate();

    public event MyDelegate myDelegate;
    public static void Main (string[] args)
    {
    MainClass p = new MainClass ();
    p.myDelegate = Test1;
    p.myDelegate ();
    Console.ReadKey ();
    }

    static void Test1()
    {
    Console.WriteLine ("test1");
    }
    }

    代码二:

      《》设计模式观察者模式《》:

      事件不能在类的外部触发,所以比较委托类型能通过对象来调用的方式就安全的多了。

  • 相关阅读:
    扫描线算法
    [Baltic 2001]Mars Maps
    Lost Cow
    李超线段树
    多种方法求解Pku3468 A Simple Problem with Integers
    陈老师的福利
    leetcode 673. 最长递增子序列的个数
    #10043.「一本通 2.2 例 1」剪花布条
    PTA7-1
    6-1 实验三哈夫曼树 (15分)
  • 原文地址:https://www.cnblogs.com/ylllove/p/6753893.html
Copyright © 2011-2022 走看看