与指针相似的代表元及事件触发覆盖
文章来源:延庆文学网 | 2021-10-29
代表元是C#中比较复杂的概念,C#中的代表元和C/C++中的函数指针非常相似使用代表元可以把代表元内部方法的引用封装起来然后通过它使用代表元引用的方法。
它有一个特性就是不需要知道被引用的方法属于那一个类对象只要函数的参数个数与返回类型与代表元对象一致。这样说可能比较抽象我下面举几个简单的例子希望能给广大初学者一些基本的认识。
//定义一个返回值为string的无参数的代表元注意这个代表元只能引用对象中返回值为string的无参数方法 delegate string MyDelegate(); public class MyClass { public string SayHello() { return \"Hello the world!\"; } } public class TestMyClass { public static void Main(string[] args) { MyClass myClass1=new MyClass(); MyDelegate myDelegate1=new MyDelegate(yHello); //下面就使用myDelegate1代替对象myClass1的SayHello方法 iteLine(myDelegate1()); //输出结果为hello the world!与调用yHello();效果相同 } }
如果代表元只有这点功能它就没有什么太大的用处了,代表元还有一个非常有用的功能就是定义复合代表元对象只有同样类型的代表元才能够复合起来 + 能定义复合代表元对象 - 从一个复合代表元中去掉一个代表元对象: delegate void MyDelegate(string s); public class MyClass { public void SayHello(string who) { iteLine( who+\"hello!\"); } public void SayGoodBye(string who) { iteLine( who+\"good bye!\"); } } public class TestMyClass { public static void Main(string[] args) { MyClass myClass1=new MyClass(); MyDelegate myDelegate,myDelegate1; myDelegate=new MyDelegate(yHello); myDelegate1=new MyDelegate(yGoodBye); myDelegate+=myDelegate1; //这样调用myDeletage就相当于同时调用了yHello和yGoodBye myDelegate(\" \"); //执行结果输出 hello! good bye! } }
大约有20多把 事件驱动是windows应用程序的重要特征C#代表元就是用于产生事件,事件就是用于在一个组件中监听这个组件的变化。下面再举一个简单的例子: //定义一个事件代理(代表元) public delegate void EventHandler(string str); //定义事件源类 class EventSource { //定义代表元作为事件源类的成员 public event EventHandler Say; public void TriggerEvent() { if(y!=null) //因为Say是个代表元所以执行Say方法所做的实际操作由注册到它的事件处理函数决定 Say(\"A event take place!\"); } } //测试 class Test { public static void Main() { EventSource aEventSource=new EventSource(); //注册事件处理函数为MyEvent 显示一串字符类似于ick+=new EventHandler(Button1_OnClick); y+=new EventHandler(MyEvent); //此处为演示事件触发过程所以就用程序自动触发 //在图形界面应用程序中,一般由用户触发事件,后由操作系统发送消息并调用处理函数 所以程序员只要注册事件处理函数 //和编写事件处理函数的代码其他就不用关心了 iggerEvent(); } //事件处理函数 public static void MyEvent(string str) { iteLine(str); } }
查看本文来源
台州卵巢炎治疗多少钱乌鲁木齐哪家白癜风医院好
惠州癫痫疾病医院
上一篇:不验证就能与网吧中陌生友聊天计划
上一篇:与对打三星暴跌至牛