21
5

委托用法,C#源代码

0
归档:2009年5月分类:C#和.NET
内容纲要

1、委托的概念
委托是C#一个非常重要的概念,也是很有用的,因为委托和事件结合起来使用可以完成很多功能(委托是事件的基础),而且可以通过委托来实现函数的匿名方法(通过将委托与命名方法或匿名方法关联,可以实例化委托)。
C#的委托类似于 C++ 中的函数指针;但是,委托是类型安全和可靠的。
2、委托的用法
委托类型声明的格式如下:
public delegate void TestDelegate(string message);delegate 关键字用于声明一个引用类型,该引用类型可用于封装命名方法或匿名方法。
为了与命名方法一起使用,委托必须用具有可接受签名的方法进行实例化。有关方法签名中允许的方差度的更多信息,请参见委托中的协变和逆变。为了与匿名方法一起使用,委托和与之关联的代码必须一起声明。
3、实现代码
下面用C#代码来说明如何使用委托(参考自微软msdn):

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

声明: 本文采用 BY-NC-SA 协议进行授权. 未标注“转”的文章均为原创,转载请注明转自: 委托用法,C#源代码

公告栏

欢迎大家来到我的博客,我是dodoro,希望我的博客能给你带来帮助。