• C# delegate & event


    public delegate void MyDelegate(string mydelegate);//声明一个delegate对象

    //实现有相同参数和返回值的函数
            public void HelloDelegate(string mydelegate)
            {
                Console.WriteLine(mydelegate);
            }

    MyDelegate mydelegate = new MyDelegate(testClass.HelloDelegate);//产生delegate对象
    mydelegate("Hello delegate");//调用

    From MSDN: [C# delegate的演进]

    class Test
    {
        delegate void TestDelegate(string s);
        static void M(string s)
        {
            Console.WriteLine(s);
        }
    
        static void Main(string[] args)
        {
            // Original delegate syntax required 
            // initialization with a named method.
            TestDelegate testDelA = new TestDelegate(M);
    
            // C# 2.0: A delegate can be initialized with
            // inline code, called an "anonymous method.匿名函式" This
            // method takes a string as an input parameter.
            TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };
    
            // C# 3.0. A delegate can be initialized with
            // a lambda expression. The lambda also takes a string
            // as an input parameter (x). The type of x is inferred by the compiler.
            TestDelegate testDelC = (x) => { Console.WriteLine(x); };
    
            // Invoke the delegates.
            testDelA("Hello. My name is M and I write lines.");
            testDelB("That's nothing. I'm anonymous and ");
            testDelC("I'm a famous author.");
    
            // Keep console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
    /* Output:
        Hello. My name is M and I write lines.
        That's nothing. I'm anonymous and
        I'm a famous author.
        Press any key to exit.
     */

    =====Declaring an event=====   
    1, To declare an event inside a class, first a delegate type for the event must be declared, if none is already declared.
    public delegate void ChangedEventHandler(object sender, EventArgs e);
    2, Next, the event itself is declared.
    public event ChangedEventHandler Changed;
    3, Invoking an event
    if (Changed != null)
    Changed(this, e);
    4, Hooking up to an event
    • Compose a new delegate onto that field.
    // Add "ListChanged" to the Changed event on "List":
    List.Changed += new ChangedEventHandler(ListChanged);
    • Remove a delegate from a (possibly composite) field.
    // Detach the event and delete the list:
    List.Changed -= new ChangedEventHandler(ListChanged);
     
  • 相关阅读:
    Sqlite && EF Code FIRST 终极解决方案 2019.5.17
    网卡 API 相关
    (依赖注入框架:Ninject ) 一 手写依赖注入
    Nlog 日志框架简单教程
    调试时候输出信息到输出窗口
    利用VS 性能探查器 解决代码性能不高问题
    Image 释放
    记一次数据丢失(电脑硬盘closed to down)的经历
    [极短]数字求和
    在博客园中使用pixijs
  • 原文地址:https://www.cnblogs.com/chayu3/p/3442122.html
Copyright © 2020-2023  润新知