反思的麻烦

本文关键字:麻烦 | 更新日期: 2023-09-27 18:33:29

如何在InvokeMember中使用方法作为参数?我的意思是

没有反射

ContainerEvents ems = new ContainerEvents();
Test ob1 = new Test(4);
Exam ob2 = new Exam(1);
FExam ob3 = new FExam(1);
Check ob4 = new Check(5);
ems.Setplus = new Super(ob1.Write);
ems.Setplus = new Super(ob2.Write);
ems.Setplus = new Super(ob3.Write);
ems.Setplus = new Super(ob4.Write);
ems.Run();

超级是代表。

通过反思我想做同样的事情

Type type1 = typeof (Test);
Type type2 = typeof (Exam);
Type type3 = typeof (FExam);
Type type4 = typeof (Check);
Type events = typeof (ContainerEvents);
object eventer = Activator.CreateInstance(events);
events.InvokeMember("Setplus",BindingFlags.InvokeMethod,null,eventer,)

但我不知道要发送什么作为参数。创建Super对象的实例?

塞特加是一个属性

public Super Setplus
{
    set { obj.activate += value; }
}

obj - 类事件的对象

public class Event
{
    public event Super activate ;
    public void act()
    {
        if (activate != null) activate();
    }
}

反思的麻烦

相当于:

ContainerEvents ems = new ContainerEvents();
Test ob1 = new Test(4);
ems.Setplus = new Super(ob1.Write);

是这样的:

object ems = Activator.CreateInstance(typeof(ContainerEvents));
object ob1 = Activator.CreateInstance(typeof(Test), new object[] { 4 });
object super = Delegate.CreateDelegate(typeof(Super), ob1, "Write");
ems.GetType().GetProperty("SetPlus").SetValue(ems, super, null);