开发者

class variables reset back to null in reflection C#

i create an instance of a Person class using reflection and execute its constructor and after that i execute another function of the person class called "Execute":

Assembly assembly = Assembly.GetEntryAssembly();
object personObject = assembly.CreateInstance("ReflectionTest.Person");

// Call Constructor
var ctor = personObject.GetType().GetConstructor(new Type[] { typeof(int) });
var obj = ctor.Invoke(new object[] { 10 });

// Call Method
MethodInfo methodInfo = personObject.GetType().GetMethod("Execute");
object obj1 = methodInfo.Invoke(personObject, null);

Th problem is that all the person class variables i instanciated in the constructor ARE NULL when i call the "Execute" method. why ? and how do i get arou开发者_运维知识库nd this?


In your example, you are invoking the default constructor with this line:

object personObject = assembly.CreateInstance("ReflectionTest.Person");

This would be the proper way to construct the object:

Assembly assembly = Assembly.GetEntryAssembly();
Type personType = assembly.GetType("ReflectionTest.Person");
object inst = Activator.CreateInstance(personType, new object[] { 10 }); 


I'm not 100%, but could casting obj to a Person help?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜