将对象与静态成员变量一起序列化为 XML [英] Serialize object along with static member variables to XML
本文介绍了将对象与静态成员变量一起序列化为 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下包含静态成员变量的对象.
I have the following object that contains a static member variable.
我想做的是序列化这个对象并将其保存为 XML.不幸的是,下面的代码似乎并没有完成这项工作.
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();
}
推荐答案
使用序列化,我们只能序列化以下属性:
With Serialization, we can only serialize properties that are:
- 公开
- 非静态
- 非只读
在这种情况下,如果要序列化no1",则必须对其进行包装,如下所示:
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;} }
}
这篇关于将对象与静态成员变量一起序列化为 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文