delegate (C# Reference)

本文介绍了委托类型的声明形式,指出委托关键字用于声明可封装命名或匿名方法的引用类型,它类似C++函数指针但更安全,是事件的基础。还说明了委托可通过命名或匿名方法实例化,以及两种实例化方式的相关信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The declaration of a delegate type takes the following form:

public delegate void TestDelegate(string message);

The delegate keyword is used to declare a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure. For applications of delegates, see Delegates and Generic Delegates.

Remarks

Delegates are the basis for Events.

A delegate can be instantiated by associating it either with a named or anonymous method. For more information, see Named Methods and Anonymous Methods.

For use with named methods, the delegate must be instantiated with a method that has an acceptable signature. For more information on the degree of variance that is allowed in the method signature, see Covariance and Contravariance in Delegates. For use with anonymous methods, the delegate and the code to be associated with it are declared together. Both ways of instantiating delegates are discussed in this section.


ExpandedBlockStart.gif 代码
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 " );
    }
}


 

转载于:https://www.cnblogs.com/sandy_liao/archive/2010/11/29/1891503.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值