C#事件

简介
任何编写过图形用户界面(GUI)软件的开发人员都熟悉事件处理编程,当用户与GUI控制进行交互时(例如点击表格上的按钮),作为上述事件的反应,就会执行一个或多个方法。没有用户的参与,事件也可能执行事件处理程序是对象的方法,是根据应用程序中发生的事件执行的。为了理解.Net框架下的事件处理模式,我们需要理解代理的概念。

C#中的代理

C#中的代理允许我们将一个类中的方法传递给其他类的对象。我们能够将类A中的方法m封装为一个代理,传递给类B,类B能够调用类A中的方法m,静态和实例方法都可以传送。C++软件开发人员应该对这一概念非常熟悉,在C++中,开发人员能够以参数的形式使用函数指针将函数传递给同理个类或其他类中的方法。代理的概念是在Visulal J++中引入的,然后又被带到了C#中。在.Net框架中C#的代理是以从System.Delegate中继承的类的形式实现的。使用代理需要4个步骤:

1、定义一个输入参数与要进行封装的方法完全相同的代理对象。

2、定义所有输入参数与在第1步中定义的代理对象相同的方法。

3、创建代理对象,并与希望封装的方法进行连接。

4、通过代理对象调用封装的方法。

下面的C#代码通过实现一个代理、4个类举例说明了上面的4个步骤:

using System;
//步骤1:定义一个具有被封装方法输入参数的代理对象

public delegate void MyDelegate(string input);
//步骤2:定义与定义的代理对象具有相同输入参数的方法

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);
}
}
//步骤3:创建代理对象,插入方法

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;
}
}
//步骤4:通过代理调用被封装的方法。

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值