Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我无法使用反射订阅我的事件_C#_Events_Reflection - Fatal编程技术网

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

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

我有一个c#桌面应用程序

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

我需要绑定到DLL中的事件

eventInfo为空

这是我的代码:

//在我的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
重载以搜索静态事件

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);