C# 反映未知子类型
我有一个类:
public class Chid1 : Parent{
public string var1{get;set;}
public string var2{get;set;}
}
public class Chid2 : Parent{
public string var3{get;set;}
public string var4{get;set;}
}
我正在从 xml 文件收集一些数据,我需要设置这些类。
所以这就是我现在可以做的:
string child = "Chid1";//from the xml
Parent instance = (Parent)Activator.CreateInstance(Type.GetType(child ) , ...);
由于 Parent 不包含有关子项的详细信息,我无法执行以下操作:
instance.var1 = "Some text from the XML";
这里是否有任何解决方案可以通过以下字符串设置子项:
Activator.SetParan(instance,"var1" , "Some text from the XML");
或者其他什么?
I have a class:
public class Chid1 : Parent{
public string var1{get;set;}
public string var2{get;set;}
}
public class Chid2 : Parent{
public string var3{get;set;}
public string var4{get;set;}
}
I am collecting some data from an xml file and I need to setup these classes.
So this is what I can do for now:
string child = "Chid1";//from the xml
Parent instance = (Parent)Activator.CreateInstance(Type.GetType(child ) , ...);
Since Parent does not containg details about the childs, I cant do:
instance.var1 = "Some text from the XML";
Is there any solution here of setting up the childs via strings like:
Activator.SetParan(instance,"var1" , "Some text from the XML");
Or something else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否考虑过在这里使用
dynamic
。这将使代码变得更加简单。此外,您不使用已知的序列化引擎还有一个原因。如果您只是将对象序列化为 XML 流中的对象,有许多现有的解决方案可以让您的生活更轻松
Have you considered using
dynamic
here. It would make the code much simpler.Additionally is there a reason you're not using a known serialization engine. If you are simply serializing objects to an from an XML stream there are a number of existing solutions that would make your life easier
为子类提供一个构造函数,然后通过第二个参数向 Activator.CreateInstance 提供参数,该实例将构造函数参数作为参数 object[]:
Give the child classes a constructor and then supply the arguments through the second argument to Activator.CreateInstance, which takes constructor args as params object[]: