词 - 反映事件
我正在尝试使用反射来获取单词中的所有事件,然后创建一个可以添加到这些事件之一的委托。到目前为止我的代码是: 感谢您的回复。
想法是将 DocumentBeforeSave 等事件的名称传递给类似于以下的方法:
EventInfo p = getEvent(this.Application, "DocumentBeforeSave");
public EventInfo getEvent(Word.Application wordApp, string eventName)
{
Type wordType = wordApp.GetType();
EventInfo[] f = wordApp.GetType().GetEvents();
EventInfo result = (from o in f
where o.Name == eventName
select o).FirstOrDefault();
return result;
}
现在,这为我提供了 Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeSaveEventHandler 的 EventInfo。对我来说,它看起来像 Word.ApplicationEvents4_DocumentBeforePrintEventHandler ,它可以使用 += 进行分配和事件处理程序;
我看到 EventInfo 有一个 AddEventHandler 方法。我希望我可以附加自己的委托来处理 DocumentBeforeSave 事件触发时的情况。
问题是,我似乎无法让代表正确。我一直在玩这个:
MethodInfo[] myArrayMethodInfo = msw.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
MethodInfo r = (from o in myArrayMethodInfo
where o.Name == "add_" + p.Name
select o).FirstOrDefault();
Delegate del = Delegate.CreateDelegate(p.EventHandlerType,r, false);
但代表总是空的。这是不可能的还是我只是做错了。
谢谢
I am trying to use reflection to get all the events in word and then create a delegate that I can add to one of these events. The code I have so far is:
Thanks for the response.
Well the idea is to pass the name of an event such as DocumentBeforeSave to a method a bit like:
EventInfo p = getEvent(this.Application, "DocumentBeforeSave");
public EventInfo getEvent(Word.Application wordApp, string eventName)
{
Type wordType = wordApp.GetType();
EventInfo[] f = wordApp.GetType().GetEvents();
EventInfo result = (from o in f
where o.Name == eventName
select o).FirstOrDefault();
return result;
}
Now this gives me an EventInfo of Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeSaveEventHandler. Which to me looks like Word.ApplicationEvents4_DocumentBeforePrintEventHandler which can assign and eventhandler with +=;
I see that the EventInfo has an AddEventHandler method. I am hoping that I can attach my own delegate to handle when the DocumentBeforeSave event fires.
The problem is, I just don't seem to be able to get the delegate right. I have been playing around with this:
MethodInfo[] myArrayMethodInfo = msw.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
MethodInfo r = (from o in myArrayMethodInfo
where o.Name == "add_" + p.Name
select o).FirstOrDefault();
Delegate del = Delegate.CreateDelegate(p.EventHandlerType,r, false);
But the Delegate is always null. Is this just not possible or am I just doing it wrong.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建表达式树。
此功能允许您在运行时将代码编译为任意委托类型。
You can create an Expression Tree.
This feature allows you to compile code at runtime into an arbitrary delegate type.