C# 我无法使用反射订阅我的事件
我有一个c#桌面应用程序 我使用反射加载DLL。DLL以字节形式加载 我需要绑定到DLL中的事件 eventInfo为空 这是我的代码: //在我的DLL中C# 我无法使用反射订阅我的事件,c#,events,reflection,C#,Events,Reflection,我有一个c#桌面应用程序 我使用反射加载DLL。DLL以字节形式加载 我需要绑定到DLL中的事件 eventInfo为空 这是我的代码: //在我的DLL中 namespace injectdll { public class Class1 { public delegate void delResponseEvent(string message); public static event delResponseEvent ResponseEve
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)
{
}
}
尝试使用
BindingFlags
重载以搜索静态事件
var eventInfo = program.GetType().GetEvent("ResponseEvent",BindingFlags.Static);
或
当使用以
Get
开头的Reflection
方法时,首先要知道的是,它们使用BindingFlags
组合来确定应该返回哪些成员,默认值是instance
和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);
你真的知道答案吗?还是你只是在猜测?@BartoszKP默认反射方法跳过私有/静态属性。这就是为什么会有定义了更具体参数的重载。@tchrikch您没有回答我的问题。您提供了两个备选方案,但尚不清楚这两个方案是否都有效以及有何区别。你核实了吗?(我并不是说你的答案一定是错的)。你应该使用公共和静态标志。顺便说一句,我没有减去1
Type type = program.GetType("injectdll.Class1");
var flags = BindingFlags.Static | BindingFlags.Public;
MethodInfo Method = type.GetMethod("hello", flags);
var eventInfo = type.GetEvent("ResponseEvent", flags);