Reflection 在C#3.0中绑定到目标方法时出错
我正在尝试使用反射连接一个代理。这就是我到目前为止所做的Reflection 在C#3.0中绑定到目标方法时出错,reflection,c#-3.0,delegates,Reflection,C# 3.0,Delegates,我正在尝试使用反射连接一个代理。这就是我到目前为止所做的 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
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");
}
但是在
Delegate d=Delegate.CreateDelegate(tDelegate,typeof(ChartHelper.ICChartHelper),miHandler)强>
行中,我遇到了错误错误绑定到目标方法
我也发现了这个问题,并试图解决同样的问题,但没有运气
我需要帮助来理解我做错了什么
谢谢您的方法是实例方法,因此您需要使用
CreateDelegate
的重载,该重载接受委托的目标,并传入声明类型的实例。例如:
Delegate d = Delegate.CreateDelegate(tDelegate, new ICChartHelper(), miHandler);
请注意,您不需要在EventInfo
上调用GetAddMethod
并使用反射调用该方法-您只需使用