C#委托(delegate)

本文介绍了C#中的委托概念,详细解释了如何通过四个步骤来使用委托:声明委托、定义委托方法、创建委托对象并调用委托方法。通过一个完整的示例展示了委托的实际应用。

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

 

转载于:https://www.cnblogs.com/libingql/p/3762254.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值