C#中:从XML实例化类 [英] C#: instantiating classes from XML

查看:311
本文介绍了C#中:从XML实例化类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所拥有的是所有实现相同的接口,但可以在引擎盖下漂亮的完全不同类的集合。我想有一个配置文件控制,该班在启动程序进入收集,采取一些看起来像

What I have is a collection of classes that all implement the same interface but can be pretty wildly different under the hood. I want to have a config file control which of the classes go into the collection upon starting the program, taking something that looks like

<class1 prop1="foo" prop2="bar"/>

和转向到这一点。

blah = new class1();
blah.prop1="foo";
blah.prop2="bar";

在一个非常通用的方式。我不知道该怎么做的事情是把字符串为prop1在配置文件中,并把它转换成代码中的实际属性访问。有没有在C#中的元编程工具,以允许?

in a very generic way. The thing I don't know how to do is take the string "prop1" in the config file and turn that into the actual property accessor in the code. Are there any metaprogramming facilities in C# to allow that?

推荐答案

您可能是更容易的类从XML序列化到/,然后可以简单地传递的XmlReader(这是读你的配置文件),以解串器,它会完成剩下的给你。

It may be easier to serialise the classes to/from xml, you can then simply pass the XmlReader (which is reading your config file) to the deserializer and it will do the rest for you..

This是系列化

有一件事我想补充的,即使反射是强大的,它需要你了解的类型,如参数等一些东西。

One thing I would like to add, even though reflection is powerful, it requires you to know some stuff about the type, such as parameters etc.

序列化到XML犯规没有那些东西,你仍然可以通过确保你写的完全限定类型名称到XML文件,所以同类型会自动加载具有类型安全。

Serializing to XML doesnt need any of that, and you can still have type safety by ensuring you write the fully qualified type name to the XML file, so the same type is automatically loaded.

这篇关于C#中:从XML实例化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆