我无法使用反射订阅我的事件
I cannot subscribe to my event using reflection
我有一个 C# 桌面应用程序。
我使用反射加载了一个 DLL。 DLL 以字节形式加载。
我需要绑定到 DLL 中的事件。
事件信息为空。
这是我的代码:
//在我的 DLL 中
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
重载以搜索 static 事件。
var eventInfo = program.GetType().GetEvent("ResponseEvent",BindingFlags.Static);
或
var eventInfo = program.GetType().GetEvent("ResponseEvent",BindingFlags.Static|BindingFlags.Instance);
使用以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);
我有一个 C# 桌面应用程序。
我使用反射加载了一个 DLL。 DLL 以字节形式加载。
我需要绑定到 DLL 中的事件。
事件信息为空。
这是我的代码:
//在我的 DLL 中
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
重载以搜索 static 事件。
var eventInfo = program.GetType().GetEvent("ResponseEvent",BindingFlags.Static);
或
var eventInfo = program.GetType().GetEvent("ResponseEvent",BindingFlags.Static|BindingFlags.Instance);
使用以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);