我有这堂课:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Grouping
{
[Serializable]
public class Group<T> : HashSet<T>
{
public Group(string name)
{
this.name = name;
}
protected Group(){}
protected Group(SerializationInfo info, StreamingContext context):base(info,context)
{
name = info.GetString("koosnaampje");
}
public override void GetObjectData(SerializationInfo info,StreamingContext context)
{
base.GetObjectData(info,context);
info.AddValue("koosnaampje", Name);
}
private string name;
public string Name
{
get { return name; }
private set { name = value; }
}
}
}
由于它继承自 HashSet,它必须实现 ISerializable,因此受保护的构造函数和 GetObjectData 方法。以前我使用 BinaryFormatter 成功地序列化和反序列化这个类。
因为我希望能够检查由序列化程序生成的输出,所以我想切换到 DataContractSerializer。
我写了这个测试:
[TestMethod]
public void SerializeTest()
{
var group = new Group<int>("ints"){1,2,3};
var serializer = new DataContractSerializer(typeof (Group<int>));
using (var stream=File.OpenWrite("group1.xml"))
{
serializer.WriteObject(stream,group);
}
using (var stream=File.OpenRead("group1.xml"))
{
group = serializer.ReadObject(stream) as Group<int>;
}
Assert.IsTrue(group.Contains(1));
Assert.AreEqual("ints",group.Name);
}
测试失败,因为 Name 属性为空!(尽管整数被(反)序列化正确)发生了什么?
编辑:它与名称支持字段是私有的无关。将其公开具有相同的结果。