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?
精彩评论