2012-05-06 97 views
0

如何使用方法作为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的实例?

Setplus是一个属性

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

OBJ - 类事件的对象

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

你为什么要使用invoke成员?在原始代码中,只需在Setplus中添加几个集合后,就可以调用'Run()'。你的代码没有多大意义。 – SimpleVar

+0

目前还不清楚你想要做什么,因此很难帮助你。编辑代码以获得逻辑名称以及我们熟悉的示例。 – SimpleVar

+2

(在Stack Overflow上展示代码时,请使用空格而不是标签--Markdown并不真的很喜欢标签......) –

回答

1

的等效:

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