动态创建注册事件
private Dictionary<string, AssemblyStruct> events = new Dictionary<string,AssemblyStruct>();
/// <summary>
/// 事件对应的调用接口
/// </summary>
public Dictionary<string, AssemblyStruct> Events
{
get { return events; }
set { events = value; }
}
/// <summary>
/// 绑定业务组件
/// </summary>
/// <param name="control">控件</param>
public void BandingEvents(Control control)
{
foreach (var eventC in Events)
{
EventInfo ei = control.GetType().GetEvent(eventC.Key);
MethodInfo doEventMethod = this.GetType().GetMethod("DoControlEnventService");
Type[] delegateParameters = GetDelegateParameterTypes(ei.EventHandlerType);
Type eventArgsType = delegateParameters[1];
MethodInfo concreteDoEventMethod = doEventMethod.MakeGenericMethod(eventArgsType);
Delegate dele = Delegate.CreateDelegate(ei.EventHandlerType, this, concreteDoEventMethod);
control.GetType().GetEvent(eventC.Key).AddEventHandler(control, dele);
}
}
public void DoControlEnventService<T>(object sender, T eventArgs) where T : System.EventArgs
{
MessageBox.Show("asdasd");
}
private Type[] GetDelegateParameterTypes(Type d)
{
if (d.BaseType != typeof(MulticastDelegate))
{
return null;
}
MethodInfo invoke = d.GetMethod("Invoke");
if (invoke == null)
{
return null;
}
ParameterInfo[] parameters = invoke.GetParameters();
Type[] typeParameters = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
typeParameters[i] = parameters[i].ParameterType;
}
return typeParameters;
}