委托C#

委托类型声明的格式如下:


public delegate void TestDelegate(string message);
delegate 关键字用于声明一个引用类型,该引用类型可用于封装命名方法或匿名方法。委托类似于 C++ 中的函数指针;但是,委托是类型安全和可靠的。有关委托的应用,请参见委托和泛型委托。


备注
委托是事件的基础。


通过将委托与命名方法或匿名方法关联,可以实例化委托。有关更多信息,请参见命名方法和匿名方法。


为了与命名方法一起使用,委托必须用具有可接受签名的方法进行实例化。有关方法签名中允许的方差度的更多信息,请参见委托中的协变和逆变。为了与匿名方法一起使用,委托和与之关联的代码必须一起声明。本节讨论这两种实例化委托的方法。


using System;
// Declare delegate -- defines required signature:
delegate void SampleDelegate(string message);


class MainClass
{
    // Regular method that matches signature:
    static void SampleDelegateMethod(string message)
    {
        Console.WriteLine(message);
    }


    static void Main()
    {
        // Instantiate delegate with named method:
        SampleDelegate d1 = SampleDelegateMethod;
        // Instantiate delegate with anonymous method:
        SampleDelegate d2 = delegate(string message)
        { 
            Console.WriteLine(message); 
        };


        // Invoke delegate d1:
        d1("Hello");
        // Invoke delegate d2:
        d2(" World");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值