Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 全局访问,XML文件(设置文件)值_C#_Settings - Fatal编程技术网

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

C# 全局访问,XML文件(设置文件)值,c#,settings,C#,Settings,我使用自定义XML保存我的应用程序设置(我对设置文件或配置文件不感兴趣)。我想阅读这些设置,并在必要时将其保留在其他课程中使用。最好的方法是什么?使用静态类还是其他方式 我想说,有一个静态类就可以了,我建议大家注意: 具有静态构造函数,其中xml文件将被解析,值将被读取并分配到相应的字段中 如果某些数据(或最坏情况下的整个xml文件)丢失,则将指定默认值 使用公共静态自动属性,该属性将只有getter。隐藏你的私人领域 编辑 从静态类的静态构造函数读取XML文件: public static

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

我想说,有一个静态类就可以了,我建议大家注意:

  • 具有静态构造函数,其中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;
        }
    }
}
公共静态类MyStaticClass
{
//这是我们逐行存储xml文件的地方
私有静态列表;
//这是类的静态构造函数
//此代码将首先运行(您不必调用它,它是自动运行的)
静态MyStaticClass()
{
_xmlLines=新列表();
使用(System.IO.StreamReader xml=new System.IO.StreamReader(“yourFile.xml”))
{
字符串行=null;
而((line=xml.ReadLine())!=null)
{
_添加(行);
}
}
//记住在这里捕捉您的异常
}
//这是“仅获取自动”属性
公共静态列表行
{
得到
{
返回xmlLines;
}
}
}
注意:这是而不是可用于生产的代码,例如解析文件的类型和逻辑由您决定,但我希望出于演示目的,代码应该可以。
如果有任何不清楚的地方,请随时询问(但请记住,您提供的信息越多,答案就越准确)。

如果您仍要从静态构造函数执行代码,请参阅我的编辑。