带有命名方法的委托与带有匿名方法的委托
2008-07-01 14:13
295 查看
委托可以与命名方法关联。使用命名方法对委托进行实例化时,该方法将作为参数传递,例如:
这被称为使用命名的方法。使用命名方法构造的委托可以封装静态方法或实例方法。在早期版本的 C# 中,命名方法是对委托进行实例化的唯一方式。但是,在不希望付出创建新方法的系统开销时,C# 使您可以对委托进行实例化,并立即指定委托在被调用时将处理的代码块。这些被称为匿名方法。
作为委托参数传递的方法必须与委托声明具有相同的签名。
委托实例可以封装静态或实例方法。
尽管委托可以使用 out 参数,但建议您不要将其用于多路广播事件委托,因为您无法知道哪个委托将被调用。
以下是声明及使用委托的一个简单示例。注意,委托 Del 和关联的方法 MultiplyNumbers 具有相同的签名
结果为:
在下面的示例中,一个委托被同时映射到静态方法和实例方法,并分别返回特定的信息。
结果为:
// Declare a delegate:
delegate void Del(int x);
// Define a named method:
void DoWork(int k) { /* ... */ }
// Instantiate the delegate using the method as a parameter:
Del d = obj.DoWork;
这被称为使用命名的方法。使用命名方法构造的委托可以封装静态方法或实例方法。在早期版本的 C# 中,命名方法是对委托进行实例化的唯一方式。但是,在不希望付出创建新方法的系统开销时,C# 使您可以对委托进行实例化,并立即指定委托在被调用时将处理的代码块。这些被称为匿名方法。
作为委托参数传递的方法必须与委托声明具有相同的签名。
委托实例可以封装静态或实例方法。
尽管委托可以使用 out 参数,但建议您不要将其用于多路广播事件委托,因为您无法知道哪个委托将被调用。
以下是声明及使用委托的一个简单示例。注意,委托 Del 和关联的方法 MultiplyNumbers 具有相同的签名
// Declare a delegate
delegate void Del(int i, double j);
class MathClass
{
static void Main()
{
MathClass m = new MathClass();
// Delegate instantiation using "MultiplyNumbers"
Del d = m.MultiplyNumbers;
// Invoke the delegate object.
System.Console.WriteLine("Invoking the delegate using 'MultiplyNumbers':");
for (int i = 1; i <= 5; i++)
{
d(i, 2);
}
}
// Declare the associated method.
void MultiplyNumbers(int m, double n)
{
System.Console.Write(m * n + " ");
}
}
结果为:
Invoking the delegate using 'MultiplyNumbers':
2 4 6 8 10
在下面的示例中,一个委托被同时映射到静态方法和实例方法,并分别返回特定的信息。
// Declare a delegate
delegate void Del();
class SampleClass
{
public void InstanceMethod()
{
System.Console.WriteLine("A message from the instance method.");
}
static public void StaticMethod()
{
System.Console.WriteLine("A message from the static method.");
}
}
class TestSampleClass
{
static void Main()
{
SampleClass sc = new SampleClass();
// Map the delegate to the instance method:
Del d = sc.InstanceMethod;
d();
// Map to the static method:
d = SampleClass.StaticMethod;
d();
}
}
结果为:
A message from the instance method.
A message from the static method.
相关文章推荐
- 温故而知新-----带有命名方法的委托和带有匿名方法的委托
- 带有命名方法的委托与带有匿名方法的委托(C# 编程指南)
- 带有命名方法的委托与带有匿名方法的委托
- 带有命名方法的委托与带有匿名方法的委托
- 带有命名方法的委托与带有匿名方法的委托(C# 编程指南)
- 命名的方法 匿名方法 对委托进行实例化
- c# 匿名方法(委托)
- 匿名方法---将代码块作为参数传递给委托
- 委托(3.匿名方法)
- 高阶函数、委托与匿名方法
- 事件与委托的匿名方法使用方法示例
- 委托、匿名方法、Lambda表达式的演进
- 委托的由来以及委托链和委托的匿名方法
- 委托-异步调用-泛型委托-匿名方法-Lambda表达式-事件
- 编写高质量代码改善C#程序的157个建议[为泛型指定初始值、使用委托声明、使用Lambda替代方法和匿名方法]
- Delegate,Action,Func,匿名方法,匿名委托,事件 (转载)
- 委托、匿名方法和 Lambda 表达式
- 泛型委托及委托中所涉及到匿名方法、Lambda表达式
- C#匿名委托和Java匿名局部内部类使用方法示例
- 从.NET中委托写法的演变谈开去(上):委托与匿名方法