我有以下模型:
public class ABaseObject
{
private Guid id = Guid.NewGuid();
public ABaseObject()
{
}
public Guid ID { get { return id; } }
}
public class ADerivedObject : ABaseObject
{
public ADerivedObject()
{
}
public string Name { get; set; }
}
public class AObjectCollection<T>
{
private List<T> items = new List<T>();
public AObjectCollection()
{
}
public IEnumerable<T> Items { get { return items; } }
public void Add(T item)
{
items.Add(item);
}
public void Save(string filePath)
{
FileStream writer = new FileStream(filePath, FileMode.Create);
DataContractSerializer s = new DataContractSerializer(typeof(T));
s.WriteObject(writer, this);
writer.Close();
}
public void Load(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
DataContractSerializer ser = new DataContractSerializer(typeof(T));
// Deserialize the data and read it from the instance.
T deserializedObj = (T)ser.ReadObject(reader, true);
reader.Close();
fs.Close();
}
}
所以基本上我希望能够做到以下几点:
var der = new ADerivedObject();
der.Name = "Test";
var col = new AObjectCollection<ADerivedObject>();
col.Add(der);
col.Save("C:\MyCollection.xml");
...
var col2 = new AObjectCollection<ADerivedObject>();
col2.Load("C:\MyCollection.xml");
序列化后,它应该类似于:
<Collection>
<Item>
<ID></ID>
<Name></Name>
</Item>
</Collection>
我玩过 DataContracts 和 XmlSerializer,但我似乎无法找到一种方法来做到这一点。