开发者

Error binding to target method in C#3.0

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜