代码之家  ›  专栏  ›  技术社区  ›  Matt Mitchell

通过反射获取事件参数

  •  2
  • Matt Mitchell  · 技术社区  · 15 年前

    我不知道如何获取事件的参数类型。

    例如,我只能看到使用methodinfo来获取参数,但是我有eventinfo或fieldinfo。

    我想要的是能够从这里得到“布尔值”:

    Public Event EventName(ByVal sender As Object, ByVal value As Boolean)
    

    理论上,我可以尝试getRaiseMethod()之类的方法,但这行不通(因为该方法根据 this link )即使这样,它也需要首先绑定方法,这意味着测试套件只需确认事件在初始化时具有特定类型的参数。

    有什么想法吗?

    2 回复  |  直到 8 年前
        1
  •  12
  •   Daniel Brückner    15 年前

    假设事件为 EventName 在类中声明 DeclaringClass 事件至少有to参数。否则你可能会收到一个异常。

    Type secondEventHandlerParameterType = 
       typeof(DeclaringClass).
       GetEvent("EventName").
       EventHandlerType.
       GetMethod("Invoke").
       GetParameters()[1].
       ParameterType;
    
        2
  •  0
  •   Ivan Kochurkin    8 年前

    我试着用丹尼尔的方法,但是 TypeInitializationException 我的PCL例外。

    以下代码对我有效,看起来更清楚:

    Type secondEventHandlerParameterType = 
       typeof(DeclaringClass).
       GetEvent("EventName").
       EventHandlerType.
       GenericTypeArguments.
       First();