首页 新闻 会员 周边

使用反射注册Action<string>事件的求助

0
悬赏园豆:100 [已解决问题] 解决于 2020-09-09 10:41

使用反射,调用方法是会写了,注册事件搞了好久搞不定,特求助大神!

DLL代码为如下,编译为:RefTest.dll

using System;

namespace RefTest
{
    public class Test
    {
        public event Action<string> OnMessage;

        public void WriteString()
        {
            Console.WriteLine("Write String");
            OnMessage?.Invoke("ActionMessage");
        }
    }
}

调用代码为:

复制代码
using System;
using System.Diagnostics;
using System.Reflection;

namespace ConsoleAppFixed
{
    class Program
    {
        static void Main(string[] args)
        {
            //反射加载
            Assembly assembly = Assembly.LoadFrom("RefTest.dll");      //加载程序集
            Type typeClass = assembly.GetType("RefTest.Test");             //获取类型(命名空间.类名)
            object obj = Activator.CreateInstance(typeClass);                  //实例化
            MethodInfo method = typeClass.GetMethod("WriteString"); //查找方法
            method.Invoke(obj, null);                                                      //方法调用


            //注册事件
            var t = typeof(Action<string>);
            Delegate mDelegate = Delegate.CreateDelegate(t, obj, "OnMessage");

            //这里不会注册了

            Console.ReadKey();
        }

        public static void Recieve()
        {
        }
    }
}
复制代码

注册接收搞不定,请大神指点,谢谢!

TabZhang的主页 TabZhang | 初学一级 | 园豆:14
提问于:2020-09-08 14:38
< >
分享
最佳答案
0

我猜测你是想这样把:

using System;
using System.Reflection;

namespace bowen1
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly assembly = Assembly.LoadFrom("./RefTest.dll"); 
            Type typeClass = assembly.GetType("RefTest.Test"); 
            object obj = Activator.CreateInstance(typeClass);
            MethodInfo method = typeClass.GetMethod("WriteString");

            var theEvent = typeClass.GetEvent("OnMessage");
            Delegate mDelegate = Delegate.CreateDelegate(typeof(Action<string>), new Program(), "Recieve");
            theEvent.AddEventHandler(obj, mDelegate);

            method.Invoke(obj, null);            

            Console.ReadKey();
        }

        public void Recieve(string message)
        {
            Console.WriteLine(message);
        }
    }
}

你对Delegate.CreateDelegate方法的理解有误

收获园豆:100
会长 | 专家六级 |园豆:12401 | 2020-09-09 10:21

感谢你的支持,我已经用接口的方式解决了。

 

https://www.codeproject.com/Answers/5278974/How-to-reflection-one-DLL-and-register-its-action#answer2

TabZhang | 园豆:14 (初学一级) | 2020-09-09 10:35

用您的方法可以编译成功,但执行报异常。

TabZhang | 园豆:14 (初学一级) | 2020-09-09 10:40

@TabZhang: 报什么错

会长 | 园豆:12401 (专家六级) | 2020-09-09 10:44

@TabZhang: 我这里成功执行了

会长 | 园豆:12401 (专家六级) | 2020-09-09 10:46
其他回答(1)
0
拓拓 | 园豆:1050 (小虾三级) | 2020-09-08 19:03

感谢回复,发贴前我已经搜索到了这个,但是需求不一样。

支持(0) 反对(0) TabZhang | 园豆:14 (初学一级) | 2020-09-09 08:50
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册