zoukankan      html  css  js  c++  java
  • C#委托(delegate)

      C#中委托(delegate)是一种安全地封装方法的类型,委托是面向对象的、类型安全的。

      使用委托的步骤:

      1、声明委托

    public delegate void DelegateHandler(string message);

      2、定义委托方法

    // Create a method for a delegate.
    public static void DelegateMethod(string message)
    {
        Console.WriteLine(message);
    }

      3、创建委托对象,并将需要传递的函数作为参数传入

    // Instantiate the delegate.
    DelegateHandler handler = DelegateMethod;

      或:

    // Instantiate the delegate.
    DelegateHandler handler = new DelegateHandler(DelegateMethod);

      4、调用委托方法

    // Call the delegate.
    handler("Hello World");

      完整示例:

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace DelegateExample
    {
        class Program
        {
            public delegate void DelegateHandler(string message);
    
            public static void DelegateMethod(string message)
            {
                Console.WriteLine(message);
            }
        
            static void Main(string[] args)
            {
                //DelegateHandler handler = DelegateMethod;
                DelegateHandler handler = new DelegateHandler(DelegateMethod);
                handler("Hello World!");
            }
        }
    }
  • 相关阅读:
    CCF CSP 201503-1 图像旋转
    CCF CSP 201403-1 相反数
    CCF CSP 201312-1 出现次数最多的数
    CCF CSP 201703-3 Markdown
    CCF CSP 201709-3 JSON查询
    CCF CSP 201709-2 公共钥匙盒
    CCF CSP 201709-1 打酱油
    CCF CSP 201604-4 游戏
    CCF CSP 201604-1 折点计数
    CCF CSP 201612-1 中间数
  • 原文地址:https://www.cnblogs.com/libingql/p/3762254.html
Copyright © 2011-2022 走看看