我使用自定义XML来保存我的应用程序设置(我对设置文件或配置文件不感兴趣)。我想阅读这些设置,并在必要时让它在其他类中使用它。什么是最好的方法?使用静态类或任何其他方式?
答案 0 :(得分:1)
我想说有一个静态课程可以完成这项工作,我建议你注意:
修改强>
从静态类的静态构造函数中读取XML文件:
public static class MyStaticClass
{
//this is where we store the xml file line after line
private static List<string> _xmlLines;
//this is the class' static constructor
//this code will be the first to run (you do not have to call it, it's automated)
static MyStaticClass()
{
_xmlLines = new List<string>();
using (System.IO.StreamReader xml = new System.IO.StreamReader("yourFile.xml"))
{
string line = null;
while ((line = xml.ReadLine()) != null)
{
_xmlLines.Add(line);
}
}
//remember to catch your exceptions here
}
//this is the get-only auto property
public static List<string> XmlLines
{
get
{
return _xmlLines;
}
}
}
注意:这是不生产就绪代码,例如,类型和逻辑解析文件取决于你,但我希望出于演示目的,代码应该没问题。 如果有任何不清楚的地方,请随时询问(但请记住,您提供的信息越多,答案就越准确)。