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!");
            }
        }
    }
  • 相关阅读:
    [POI2013]LUK-Triumphal arch
    [CF1149C](Tree Generator)
    NOI2018归程
    [CF191](Fools and Roads)
    [CF700E](Cool Slogans)
    我石乐志
    想题的时候不要颓废
    人不能忘耻
    反思
    中考加油!
  • 原文地址:https://www.cnblogs.com/libingql/p/3762254.html
Copyright © 2011-2022 走看看