C#委托(delegate)

天大地大妈咪最大 提交于 2020-01-02 07:11:32

  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!");
        }
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!