简体   繁体   English

通过反射获取事件参数

[英]Get event parameters via reflection

I can't work out how to get the parameter types for an event. 我无法弄清楚如何获取事件的参数类型。

For instance, I can only see using a MethodInfo to get parameters, but I have either an EventInfo or a FieldInfo. 例如,我只能看到使用MethodInfo来获取参数,但我有一个EventInfo或FieldInfo。

What I want is to be able to get 'Boolean' from this: 我想要的是能够从这里得到'布尔':

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

I could theoretically try something like GetRaiseMethod() but that won't work (because that method returns null as per this link ) and even if it did it would require a method binding first and this is meant to be for a test suite just confirming that the event has a certain typed parameter at initialisation. 我理论上可以尝试类似GetRaiseMethod()的东西,但这不起作用(因为该方法根据此链接返回null),即使它确实需要首先进行方法绑定,这意味着只需要确认测试套件事件在初始化时具有某个类型参数。

Any ideas? 有任何想法吗?

You can get the type of the second parameter as follows assuming the event EventName is declared in the class DeclaringClass and the event has at least to parameters. 假设事件EventNameEventName类中DeclaringClass且事件至少包含参数,您可以获得第二个参数的类型,如下所示。 Else you will probably receive an exception. 否则你可能会收到一个例外。

Type secondEventHandlerParameterType = 
   typeof(DeclaringClass).
   GetEvent("EventName").
   EventHandlerType.
   GetMethod("Invoke").
   GetParameters()[1].
   ParameterType;

I tried to use Daniel solution but got the TypeInitializationException exception in my PCL. 我尝试使用Daniel解决方案,但在我的PCL中获得了TypeInitializationException异常。

The following code works for me and looks more clear: 以下代码对我有用,看起来更清晰:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM