Serialize object along with static member variables to XML [duplicate]

断了今生、忘了曾经 提交于 2019-12-24 16:16:52

问题


I have the following object that contains a static member variable.

What I would like to do is serialize this object and save it to XML. Unfortunately, the code below does not seem to do the job.

I would appreciate any help in getting this working please.

[Serializable]
public class Numbers
{
    public int no;
    public static int no1;
    public SubNumbers SubNumber;
}

[Serializable]
public class SubNumbers
{
    public int no;
    public static int no2;
}

[TestMethod]
public void Serialize_Object_with_Static_Property_test()
{
    Numbers a = new Numbers();
    a.no = 12;
    Numbers.no1 = 345243;
    SubNumbers s = new SubNumbers();
    s.no = 459542; 
    SubNumbers.no2 = 9999999;
    a.SubNumber = s;
    String filename = @"a1.txt";
    FileStream fs = new FileStream(filename, FileMode.Open);
    XmlSerializer x = new XmlSerializer(typeof(Numbers));
    x.Serialize(fs, a); 
    fs.Close(); 
}

回答1:


With Serialization, we can only serialize properties that are:

  • Public
  • Not static
  • Not read Only

In this case, if you want to serialize "no1", you must wrap it, like this:

[Serializable]
public class Numbers
{
    public int no;
    public static int no1;
    public SubNumbers SubNumber;

    public int no1_Serialize {get {return no1;} set {no1 = value;} }
}


来源:https://stackoverflow.com/questions/17222900/serialize-object-along-with-static-member-variables-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!