【问题标题】:Saving a Class of my variables to XML File将我的变量类保存到 XML 文件
【发布时间】:2016-01-08 12:38:51
【问题描述】:

我创建了一个名为“VNCVars.cs”的类,我希望能够将与 VNCVars 中的所有变量关联的数据保存到 XML 文件中,以便在启动时将它们重新加载。我有另一个名为“SaveData.cs”的类,其中包含生成 XML 文件的代码。

我编写了可以运行的代码,但我的 XML 文件始终为空.....有人能指出我错过了什么吗??

public class VNCVars
{
    //Global Variables for VNC 1 Location
    //VNC File Location 1 Get and Set routines
    private static string strVNC1Location;
    public static string VNC1Location
    {
        get { return strVNC1Location; }
        set { strVNC1Location = value; }
    }


    //Global Variables for VNC 2 Location
    //VNC File Location 2 Get and Set routines
    private static string strVNC2Location;
    public static string VNC2Location
    {
        get { return strVNC2Location; }
        set { strVNC2Location = value; }
    }


    //Global Variables for VNC 3 Location
    //VNC File Location 3 Get and Set routines
    private static string strVNC3Location;
    public static string VNC3Location
    {
        get { return strVNC3Location; }
        set { strVNC3Location = value; }
    }
}

public class SaveXML
{

    public static void SaveData()
    {
        var SaveData = new VNCVars();

        XmlSerializer sr = new XmlSerializer(typeof(VNCVars));
        TextWriter writer = new StreamWriter(@"c:\Fanuc\SetupVars.xml");
        sr.Serialize(writer, SaveData);
        writer.Close();
    }


}

最后在我的表单上,我目前只有一个按钮,点击后会出现以下情况...

    private void button2_Click(object sender, EventArgs e)
    {
        SaveXML.SaveData();
    }

非常感谢任何帮助....

【问题讨论】:

  • 你不能使用这样的静态字段序列化一个类。使字段非静态。
  • 我只是想说构造函数在哪里
  • 如果我将它们设为非静态,那么我将无法从我拥有的每个表单(即 VNCVars.VNC1Location)中访问变量。对于基本问题,我很抱歉,但我对 C# 编程相当陌生。

标签: c# xml class save


【解决方案1】:

您应该使用实例属性而不是静态属性。

然后您可以使用单例模式只保留此类的一个实例。

【讨论】:

【解决方案2】:

如果你需要有静态变量并且不想让这个类成为单例,解决方法是包装静态变量:

[XmlElement("VNC1Location")]
public string VNC1LocationLocal
{
    get
    {
        return VNC1Location;
    }
    set
    {
        VNC1Location = value;
    }
}

【讨论】:

  • 好的,我已将它添加到我的 VNCVars 类中,当我生成 XML 文件时,VNC1LocationLocal 就在那里,其中包含我输入到公共静态字符串 VNCLocation1 中的值。以及私有静态字符串 strVNC1Location;公共静态字符串 VNC1Location { 获取 { 返回 strVNC1Location; } 设置 { strVNC1Location = 值; } } 我需要对应的公共字符串 VNC1LocationLocal { get { return VNC1Location; } 设置 { VNC1Location = 值; } } 让它工作??
  • 是的,您需要VNC1LocationLocal 属性(名称无关)来序列化VNC1Location 静态属性。我忘了我的代码会在 xml 中生成 <VNC1LocationLocal> 元素。您需要使用所需的 xml 名称添加 XmlElement 属性以生成正确的 xml。我已经更正了我的答案。
  • 它对你有用吗?或者您还有其他问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
  • 2018-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2020-06-30
相关资源
最近更新 更多