现在不能测试代码,但如果使用
this.Application.GetType().GetEvent("DocumentBeforeClose").AddEventHandler(this.Application,Delegate.CreateDelegate(ty, this, "test",false));
见this.Application,而不是这的addEventHandler通话。
更新: 现在,我可以测试代码,并且如果将“this”更改为“this.Application”,就可以正常工作,如前所述。这里是一个完整的代码:
namespace WordTestAddin
{
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Type ty = this.Application.GetType().GetEvent("DocumentBeforeClose").EventHandlerType;
var testDelegate = Delegate.CreateDelegate(ty, this, "test", false);
this.Application.GetType().GetEvent("DocumentBeforeClose").AddEventHandler(this.Application, testDelegate);
}
void test(Word.Document Doc, ref bool Cancel)
{
System.Windows.Forms.MessageBox.Show("test");
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO generated code
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
因此,确保您的“测试”方法有一个有效的签名。还要确保,“测试”是确切的方法名称,而不是“测试”或其他。
该异常提及哪个参数?例外是否说*为什么*争论被拒绝?你有没有试图将这个冗长的陈述分解成多个陈述,以便你能够找出原因? – 2011-02-07 14:58:45
嗨,我已经在很多方面打破了这个说法,我总是得到一个参数异常 - 错误绑定到Delegate.CreateDelegate调用的目标方法。我一直在想我正在使用错误的超载或错误地传递目标。谢谢 – Beats 2011-02-07 23:15:15