下面是一个非常简单的实现,没有考虑错误处理之类的,你可以参考一下。另外,建议你看一下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);