匿名委托

王朝百科·作者佚名  2010-07-29  
宽屏版  字体: |||超大  

匿名委托的叫法并不准确,准确的应该叫做匿名方法。

在 2.0 之前的 C# 版本中,声明委托的唯一方法是使用命名方法。C# 2.0 引入了匿名方法,而在 C# 3.0 及更高版本中,Lambda 表达式取代了匿名方法,作为编写内联代码的首选方式。

要将代码块传递为委托参数,创建匿名方法则是唯一的方法。

通过使用匿名方法,由于您不必创建单独的方法,因此减少了实例化委托所需的编码系统开销。

示例:

不使用匿名方法:

static void Main(string[] args)

{

Thread thread = new Thread(new ThreadStart(Run));

// 或 Thread thread = new Thread(Run); // c# 2.0 或以后版本支持

thread.Start();

}

static void Run()

{

// 要运行的代码 ...

}

使用匿名方法:

static void Main(string[] args)

{

Thread thread = new Thread(delegate()

{

// 要运行的代码

});

// 或 Thread thread = new Thread(new ThreadStart(delegate()

//{

// // 要运行的代码

//}));

thread.Start();

}

使用Lambda 表达式:

static void Main(string[] args)

{

Thread thread = new Thread(() =>

{

// 要运行的代码

});

// 或 Thread thread = new Thread(new ThreadStart(() =>

//{

// // 要运行的代码

//}));

thread.Start();

}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝百科 版权所有