我知道 EventInfo.AddEventHandler(...)
方法,该方法可用于将处理程序附加到事件.但是,如果我什至无法定义事件处理程序的正确签名,例如,我什至没有对处理程序预期的事件参数的引用,该怎么办?
I know about EventInfo.AddEventHandler(...)
method which can be used to attach handler to an event. But what should be done if i can not even define proper signature of the event handler, as in, i don't even have reference to the event args expected by the handler?
我会用正确的代码解释问题.
I will explain the problem with the proper code.
//解决方案中所有可用的场景,零反射场景.
// Scenario when I have everything available in my solution, Zero Reflection Scenario.
internal class SendCommentsManager
{
public void Customize(IRFQWindowManager rfqWindowManager)
{
rfqWindowManager.SendComment += HandleRfqSendComment;
}
private void HandleRfqSendComment(object sender, SendCommentEventArgs args)
{
args.Cancel = true;
}
}
现在,我想通过使用反射来实现相同的目标.我已经能够弄清楚其中的大部分,但是当我将委托附加到事件时(使用 AddEventHandler
)它会抛出 "Error binding to target method."
异常.
Now, I want to achieve the same objective by using reflection. I have been able to figure out most of it but when i attach a delegate to the event (using AddEventHandler
) it throws "Error binding to target method."
exception.
我了解此异常背后的原因,将错误的委托附加到事件.但必须有某种方法来实现这一点.
I understand the reason behind this exception, attaching a wrong delegate to an event. But there must be some way to achieve this.
internal class SendCommentsManagerUsingReflection
{
public void Customize(IRFQWindowManager rfqWindowManager)
{
EventInfo eventInfo = rfqWindowManager.GetType().GetEvent("SendComment");
eventInfo.AddEventHandler(rfqWindowManager,
Delegate.CreateDelegate(eventInfo.EventHandlerType, this, "HandleRfqSendComment"));
//<<<<<<<<<<ABOVE LINE IS WHERE I AM GOING WRONG>>>>>>>>>>>>>>
}
private void HandleRfqSendComment(object sender, object args)
{
Type sendCommentArgsType = args.GetType();
PropertyInfo cancelProperty = sendCommentArgsType.GetProperty("Cancel");
cancelProperty.SetValue(args, true, null);
}
}
我认为您的代码失败了,因为 HandleRfqSendComment
是私有的.相反,您可以直接为该方法创建一个委托,而无需将其名称传递给 CreateDelegate
.然后,您需要使用以下方法将委托转换为所需的类型:
I think your code is failing because the HandleRfqSendComment
is private. Instead you could directly create a delegate to that method, without passing its name to CreateDelegate
. You would then need to convert the delegate to the required type, using the following method :
public static Delegate ConvertDelegate(Delegate originalDelegate, Type targetDelegateType)
{
return Delegate.CreateDelegate(
targetDelegateType,
originalDelegate.Target,
originalDelegate.Method);
}
在您的代码中,您可以按如下方式使用此方法:
In your code, you could use this method as follows :
EventInfo eventInfo = rfqWindowManager.GetType().GetEvent("SendComment");
Action<object, object> handler = HandleRfqSendComment;
Delegate convertedHandler = ConvertDelegate(handler, eventInfo.EventHandlerType);
eventInfo.AddEventHandler(rfqWindowManager, convertedHandler);
这篇关于如何使用反射将事件处理程序附加到事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!