当我尝试序列化自己从ReadOnlyCollection派生的类时,我得到错误:
输入' MyReadOnlyCollection`1 [[System.String,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]' CollectionDataContractAttribute属性是一个无效的集合类型,因为它没有默认的构造函数。
现在错误有意义,它是真的我没有默认构造函数。但是我能够使用DataContractSerializer序列化ReadOnlyCollection,即使ReadOnlyCollection没有无参数的默认构造函数。
// OK
ReadOnlyCollection<string> readOnlyCollection = new ReadOnlyCollection<string>(new List<string> { "a", "b", "c" });
string result1 = Serialize(readOnlyCollection);
// Throws InvalidDataContractException
MyReadOnlyCollection<string> myReadOnlyCollection = new MyReadOnlyCollection<string>(new List<string> { "a", "b", "c" });
string result2 = Serialize(myReadOnlyCollection);
public static string Serialize(object o)
{
var serializer = new DataContractSerializer(o.GetType());
var stringBuilder = new StringBuilder();
using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder))
{
serializer.WriteObject(xmlWriter, o);
}
return stringBuilder.ToString();
}
[CollectionDataContract]
public class MyReadOnlyCollection<T> : ReadOnlyCollection<T>
{
public MyReadOnlyCollection(IList<T> list) : base(list)
{
}
}
两个问题:
更新 我已在上面添加了我的派生类
答案 0 :(得分:1)
How should I serialize my derived class correctly?
要正确地序列化派生类,你应该做这样的事情
[DataContract]
public class MyReadOnlyCollection<T>:ReadOnlyCollection<T>
{
public MyReadOnlyCollection(IList<T> list) : base(list)
{
}
}
编辑
您无法使用[CollectionDataContract]
,因为它不能完全满足集合类型要求,因为添加方法缺失,因此该类型不被视为集合类型