Error binding to target method in C#3.0

心已入冬 提交于 2019-12-24 07:55:45

问题


I am trying to hook Up a Delegate Using Reflection. This is what I have done so far

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");
        }

But in the

Delegate d = Delegate.CreateDelegate(tDelegate,typeof(ChartHelper.ICChartHelper), miHandler);

line, I am encountering the error Error binding to target method

I have also found the discusion here and tried to solve the same but with no luck.

I need help to understand what wrong I am doing?

Thanks


回答1:


Your method is an instance method, so you need to use an overload of CreateDelegate which takes the target of the delegate, and pass in an instance of the declaring type. For example:

Delegate d = Delegate.CreateDelegate(tDelegate, new ICChartHelper(), miHandler);

Note that you don't need to call GetAddMethod on the EventInfo and invoke that using reflection - you can just use EventInfo.AddEventHandler.



来源:https://stackoverflow.com/questions/3861322/error-binding-to-target-method-in-c3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!