Delegates in C#

本文介绍 C# 中委托的基本概念及其四步使用流程:声明匹配签名的委托对象、定义符合该签名的方法、创建委托实例并绑定方法、通过委托调用绑定的方法。

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

A delegate in C# allows you to pass methods of one class to objects of other classes that can call those methods. You can pass method m in Class A, wrapped in a delegate, to class B and Class B will be able to call method m in class A. You can pass both static and instance methods. This concept is familiar to C++ developers who have used function pointers to pass functions as parameters to other methods in the same class or in another class. The concept of delegate was introduced in Visulal J++ and then carried over to C#. C# delegates are implemented in .Net framework as a class derived from System.Delegate. Use of delegate involves four steps.

1. Declare a delegate object with a signature that exactly matches the method signature that you are trying to encapsulate.
2. Define all the methods whose signatures match the signature of the delegate object that you have defined in step 1.
3. Create delegate object and plug in the methods that you want to encapsulate.
4. Call the encapsulated methods through the delegate object.

The following C# code shows the above four steps implemented using one delegate and four classes. Your implementation will vary depending on the design of your classes.

using System;
//Step 1. Declare a delegate with the signature of the encapsulated method
public delegate void MyDelegate(string input);
//Step 2. Define methods that match with the signature of delegate declaration
class MyClass1{
public void delegateMethod1(string input){
Console.WriteLine("This is delegateMethod1 and the input to the method is {0}",input);
}
public void delegateMethod2(string input){
Console.WriteLine("This is delegateMethod2 and the input to the method is {0}",input);
}
}
//Step 3. Create delegate object and plug in the methods
class MyClass2{
public MyDelegate createDelegate(){
MyClass1 c2=new MyClass1();
MyDelegate d1 = new MyDelegate(c2.delegateMethod1);
MyDelegate d2 = new MyDelegate(c2.delegateMethod2);
MyDelegate d3 = d1 + d2;
return d3;
}
}
//Step 4. Call the encapsulated methods through the delegate
class MyClass3{
public void callDelegate(MyDelegate d,string input){
d(input);
}
}
class Driver{
static void Main(string[] args){
MyClass2 c2 = new MyClass2();
MyDelegate d = c2.createDelegate();
MyClass3 c3 = new MyClass3();
c3.callDelegate(d,"Calling the delegate"wink.gif;
}
}

转载于:https://www.cnblogs.com/dotrai/archive/2006/03/02/341529.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值