我想在伪代码中动态设置自定义事件处理程序的列表,如下所示:

FieldInfo[] fieldInfos = this.GetType().GetFields(
     BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

foreach (FieldInfo fieldInfo in fieldInfos)
{
    if this.fieldInfo.GetType() = TypeOf(CustomEventHandler<this.fieldInfo.Name>) {
        this.fieldInfo.Name += new CustomEventHandler<this.fieldInfo.Name>(OnChange<this.fieldInfo.Name>);
    }
}

我找不到正确的语法吗?

最佳答案

用GetEvents代替GetFields怎么样?

    var t = something.GetType();

    var eventInfos = t.GetEvents();

    foreach (var info in eventInfos)
    {
        if (info.EventHandlerType == TypeOf(CustomEventHandler<this.fieldInfo.Name>)
                info.AddEventHandler(...);
    }

我不太确定类型比较,但是话又说回来,fieldInfo.Name不能在这样的泛型中使用。

10-08 11:02