我正在尝试使用反射来连接代理。这就是我到目前为止所做的事情
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Data;
using System.Threading;
using System.IO;
using System.Reflection;
using System.Windows;
namespace ChartHelper
{
public class ICChartHelper
{
public void RefreshChart()
{
try
{
Assembly myobj = Assembly.LoadFrom(@"C:\sample.dll");
foreach (Type mytype in myobj.GetTypes())
{
if (mytype.IsClass == true)
{
if (mytype.FullName.EndsWith("." + "ICAutomationProxy"))
{
// create an instance of the object
object ClassObj = Activator.CreateInstance(mytype);
// var eventTypes = mytype.GetEvents();
EventInfo evClick = mytype.GetEvent("OnRefreshCompleted");
Type tDelegate = evClick.EventHandlerType;
MethodInfo miHandler =
typeof(ChartHelper.ICChartHelper)
.GetMethod("RefreshApplication",
BindingFlags.NonPublic | BindingFlags.Instance);
Delegate d = Delegate.CreateDelegate(tDelegate,typeof(ChartHelper.ICChartHelper), miHandler);
MethodInfo addHandler = evClick.GetAddMethod();
Object[] addHandlerArgs = { d };
addHandler.Invoke(ClassObj, addHandlerArgs);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
private void RefreshApplication(Object sender, EventArgs e)
{
MessageBox.Show("Bingo");
}
但是在
委托d = Delegate.CreateDelegate(tDelegate,typeof(ChartHelper.ICChartHelper),miHandler);
行,我遇到错误Error binding to target method
我也发现了here并试图解决同样但没有运气。
我需要帮助才能理解我在做什么?
由于
答案 0 :(得分:3)
您的方法是一个实例方法,因此您需要使用CreateDelegate
的重载来获取委托的目标,并传入声明类型的实例。例如:
Delegate d = Delegate.CreateDelegate(tDelegate, new ICChartHelper(), miHandler);
请注意,您无需在GetAddMethod
上致电EventInfo
并使用反射调用该功能 - 您只需使用EventInfo.AddEventHandler
。