我要做的是将 SomeInt 基于字段具有默认值的字段。IE。
public class SomeClass
{
public SomeClass() { }
int someInt = 10;
public string SomeString { get; set; }
public int SomeInt
{
get { return someInt; }
set { someInt = value; }
}
}
然后,如果未提供 SomeInt 值,则当序列化程序反序列化对象时,仍会设置默认值。
编辑:更新
添加了使用 XML 序列化程序的示例应用程序。现在要切换类类型,只需取消注释#define serialize
第 2 行中的语句。
//uncomment for serialization
//#define serialize
using System;
using System.IO;
using System.Xml.Serialization;
namespace TestSerializer
{
class Program
{
static void Main(string[] args)
{
#if serialize
SomeClass some = new SomeClass();
some.SomeString = "abc";
XmlSerializer serializer = new XmlSerializer(some.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, some);
File.WriteAllText("D:\\test.xml", writer.ToString());
}
#else
XmlSerializer serializer = new XmlSerializer(typeof(SomeClass));
using (StringReader reader = new StringReader(File.ReadAllText("D:\\test.xml")))
{
var o = serializer.Deserialize(reader) as SomeClass;
if (o != null)
Console.WriteLine(o.SomeInt);
}
Console.ReadKey();
#endif
}
}
#if serialize
[Serializable]
public class SomeClass
{
public SomeClass() { }
public string SomeString { get; set; }
}
#else
[Serializable]
public class SomeClass
{
public SomeClass() { }
private int someInt = 10;
public string SomeString { get; set; }
public int SomeInt
{
get { return someInt; }
set { someInt = value; }
}
}
#endif
}