在反射 C# 中类变量重置回 null
我使用反射创建 Person 类的实例并执行其构造函数,然后执行 person 类的另一个名为“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);
问题是,当我调用时,我在构造函数中实例化的所有 person 类变量均为 NULL “执行”方法。为什么 ?我该如何解决这个问题?
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 around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的示例中,您使用以下行调用默认构造函数:
这将是构造对象的正确方法:
In your example, you are invoking the default constructor with this line:
This would be the proper way to construct the object:
我不是 100%,但是将 obj 转换为 Person 有帮助吗?
I'm not 100%, but could casting obj to a Person help?