首页 新闻 搜索 专区 学院

从配置文件中取出多个方法名及程序集路径,将配置文件中的一组方

0
悬赏园豆:100 [已解决问题] 解决于 2008-04-07 10:44
在主程序中有一个事件 <BR>Main() <BR>{ <BR>&nbsp;&nbsp;&nbsp;Class&nbsp;c=new&nbsp;Class(); <BR>&nbsp;&nbsp;&nbsp;//一般的事件绑定是这样的,这里使用了匿名方法,现在希望这个事件绑定的多方法是从配置文件里取的(配置文件中的方法签名与事件委托的签名是相同的) <BR>&nbsp;&nbsp;&nbsp;c.TestEvent+=delegate(object&nbsp;sender,EventArgs&nbsp;e) <BR>&nbsp;&nbsp;&nbsp;{ <BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//do&nbsp;something <BR>&nbsp;&nbsp;&nbsp;} <BR>&nbsp;&nbsp;&nbsp;c.TestEvent+=delegate(object&nbsp;sender,EventArgs&nbsp;e) <BR>&nbsp;&nbsp;&nbsp;{ <BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//do&nbsp;something2 <BR>&nbsp;&nbsp;&nbsp;} <BR>} <BR>大致用到的内容是反射、委托、事件,肯请指点下
lexus的主页 lexus | 初学一级 | 园豆:0
提问于:2008-04-05 21:36
< >
分享
最佳答案
0
下面是一个非常简单的实现,没有考虑错误处理之类的,你可以参考一下。另外,建议你看一下MSDN上的这一篇文章: http://msdn2.microsoft.com/en-us/library/ms228976.aspx 晕了,代码发不全。从这里下载吧: http://www.cnblogs.com/Files/deerchao/EventReflection.zip --------------- app.config: ------------------- <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="TestClass.TestEvent.Handlers" value="EventReflection.StaticHandler.Handler1;EventReflection.InstanceHandler.Handler2"/> </appSettings> </configuration> ----------------------- program.cs ---------------------- using System; using System.Configuration; using System.Reflection; namespace EventReflection { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { TestClass c = new TestClass(); //BindEventsNonReflection(c); BindEventsWithReflection(c); c.Run(); Console.ReadKey(); } private static void BindEventsWithReflection(TestClass c) { //first get the string form of handlers from app.config string s = ConfigurationManager.AppSettings["TestClass.TestEvent.Handlers"]; //split it to get all handlers string[] handlers = s.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); //we need EventInfo to add a delegate to the event EventInfo evnt = c.GetType().GetEvent("TestEvent"); Type handlerType = evnt.EventHandlerType; foreach (string handlerName in handlers) { //split the string into class name and method name int indexOfDot = handlerName.LastIndexOf('.'); string className = handlerName.Substring(0, indexOfDot); string methodName = handlerName.Substring(indexOfDot + 1);
deerchao | 大侠五级 |园豆:8167 | 2008-04-05 22:46
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册