Skip to main content
 首页 » 编程设计

c#之我无法使用反射订阅我的事件

2024年08月06日32bonelee

我有一个 C# 桌面应用程序。

我使用反射加载 DLL。 DLL 以字节形式加载。

我需要绑定(bind)到 DLL 中的事件。

eventInfo 为空。

这是我的代码:

//在我的动态链接库中

namespace injectdll 
{ 
    public class Class1 
    { 
        public delegate void delResponseEvent(string message); 
        public static event delResponseEvent ResponseEvent; 
        public static void hello() 
        { 
            ResponseEvent("hello andy"); 
        } 
    } 
} 

//在我的桌面应用程序中

    private void button1_Click(object sender, EventArgs e) 
    { 
        try 
        { 
            byte[] bytes = System.IO.File.ReadAllBytes(@"C:\Users\Andrew\Desktop\testbytes\injectdll\injectdll\bin\Debug\injectdll.dll"); 
            Assembly program = Assembly.Load(bytes); 
            Type type = program.GetType("injectdll.Class1"); 
            MethodInfo Method = program.GetTypes()[0].GetMethod("hello"); 
            type.InvokeMember("hello", System.Reflection.BindingFlags.InvokeMethod, System.Type.DefaultBinder, "", null); 
            var eventInfo = program.GetType().GetEvent("ResponseEvent"); 
 
            //eventinfo is null? 
        } 
        catch (Exception ex) 
        { 
 
        } 
    } 

请您参考如下方法:

使用以 Get 开头的 Reflection 方法时,首先要知道的是它们使用 BindingFlags 组合来确定应该返回哪些成员,默认是 instance 和 public 成员。现在,由于您的方法和事件是 static 和 public,因此您需要指定这些标志:

Type type = program.GetType("injectdll.Class1");  
var flags = BindingFlags.Static | BindingFlags.Public; 
MethodInfo Method = type.GetMethod("hello", flags); 
var eventInfo = type.GetEvent("ResponseEvent", flags);