委托(3.匿名方法)
来源:互联网 发布:为什么需要编程语言 编辑:程序博客网 时间:2024/06/08 08:34
在 2.0 之前的 C# 版本中,声明委托的唯一方法是使用命名方法。C# 2.0 引入了匿名方法。
要将代码块传递为委托参数,创建匿名方法则是唯一的方法。
例如:
C#
// Create a handler for a click event
button1.Click += delegate (System.Object o, System.EventArgs e) {
System.Windows.Forms.MessageBox.Show("Click!");
};
或
C#
// Create a delegate instance
delegate void
// Instantiate the delegate using an anonymous method
如果使用匿名方法,则不必创建单独的方法,因此减少了实例化委托所需的编码系统开销。
例如,如果创建方法所需的系统开销是不必要的,在委托的位置指定代码块就非常有用。启动新线程即是一个很好的示例。无需为委托创建更多方法,线程类即可创建一个线程并且包含该线程执行的代码。
C#
//不理解这个例子:System.Threading.Thread t1 = new System.Threading.Thread(…)的意思
void StartThread()
{
System.Threading.Thread t1 = new System.Threading.Thread ( //下面的是参数
delegate ()
{
System.Console.Write("Hello, "); System.Console.WriteLine("World!");
}
);
t1.Start();
}
1. 匿名方法的参数的范围是 anonymous-method-block。
2. 在目标在块外部的匿名方法块内使用跳转语句(如 goto、break 或 continue)是错误的。在目标在块内部的匿名方法块外部使用跳转语句(如 goto、break 或 continue)也是错误的。
3. 如果局部变量和参数的范围包含匿名方法声明,则该局部变量和参数称为该匿名方法的外部变量或捕获变量。例如,下面代码段中的 n 即是一个外部变量:
C#
int n = 0;
System.Console.WriteLine("Copy #:{0}", ++n);
};
与局部变量不同,外部变量的生命周期一直持续到引用该匿名方法的委托符合垃圾回收的条件为止。对 n 的引用是在创建该委托时捕获的。
4. 匿名方法不能访问外部范围的 ref 或 out 参数。
5. 在 anonymous-method-block 中不能访问任何不安全代码。
下面的示例演示实例化委托的两种方法:
·使委托与匿名方法关联。
·使委托与命名方法 (DoWork) 关联。
两种方法都会在调用委托时显示一条消息。
C#
// Declare a delegate
delegate void Printer(string s);
class TestClass
{
static void
{
// Instatiate the delegate type using an anonymous method:
Printer p = delegate(string j) { System.Console.WriteLine(j); };
// Results from the anonymous delegate call:
p("The delegate using the anonymous method is called.");
// The delegate instantiation using a named method "DoWork":
p = new Printer(TestClass.DoWork);
// Results from the old style delegate call:
p("The delegate using the named method is called.");
}
// The method associated with the named delegate:
static void DoWork(string k)
{
System.Console.WriteLine(k);
}
}
The delegate using the anonymous method is called.
The delegate using the named method is called
来自:
http://msdn2.microsoft.com/zh-cn/library/0yw3tz5k(VS.80).aspx
- 委托(3.匿名方法)
- 委托三(匿名方法)
- 委托(匿名方法捕获外部变量)
- 委托(4)匿名方法
- C# 匿名方法 委托
- 使用匿名方法 委托
- 委托_匿名方法
- C# 委托,匿名方法,范型委托
- 泛型委托匿名方法
- 委托,匿名方法,λ 表达式
- C#委托-使用匿名方法
- 委托、事件与匿名方法
- C# 委托 事件 匿名方法
- 委托,匿名方法,lambda表达式
- c#匿名方法调用委托
- 委托(3.匿名方法、lambda、闭包、foreach)
- 委托的匿名方法简单例子(2。0实现)
- 带有命名方法的委托与带有匿名方法的委托(C# 编程指南)
- AboutUs-详细说明
- 百度排名NO.1是怎样SEO成功的
- 解决了c#捕获sql错误号的问题和将sql连接用application放在global中作全局变量问题
- Linux和DOS的FORMAT命令区别
- 详细讲解 Linux操作系统下文件解压缩的技巧
- 委托(3.匿名方法)
- 忠告:网页设计必须注意的29个问题
- POJ 1273 Drainage Ditches POJ 1274 The Perfect Stall 最大流简单题
- 技巧和诀窍:在IIS 7.0上使用自签证书来启用SSL
- SQL语句
- C语言的常用库函数
- 编码字符集与Java -Java World乱码问题根源之所在
- vs2003 asp.net中直接输出wml,并利用C#做动态页面的控制,不使用微软的移动控件
- Java桌面应用展望