全局访问,XML文件(设置文件)值

时间:2013-11-16 00:43:19

标签: c# settings

我使用自定义XML来保存我的应用程序设置(我对设置文件或配置文件不感兴趣)。我想阅读这些设置,并在必要时让它在其他类中使用它。什么是最好的方法?使用静态类或任何其他方式?

1 个答案:

答案 0 :(得分:1)

我想说有一个静态课程可以完成这项工作,我建议你注意:

  • 使用静态构造函数,其中将解析xml文件并读取值并将其分配到相应的字段中。
  • 如果缺少某些数据(或最坏情况下的整个xml文件),则会分配默认值
  • 使用公共静态自动属性,它只有getter。隐藏您的私人领域。

修改

从静态类的静态构造函数中读取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;
        }
    }
}

注意:这是生产就绪代码,例如,类型和逻辑解析文件取决于你,但我希望出于演示目的,代码应该没问题。 如果有任何不清楚的地方,请随时询问(但请记住,您提供的信息越多,答案就越准确)