IList的数据协定序列化
我有以下代码,其中我尝试将列表序列化到文件
public static void Serialize<T>(this IList<T> list, string fileName)
{
try
{
var ds = new DataContractSerializer(typeof(T));
using (Stream s = File.Create(fileName))
ds.WriteObject(s, list);
}
catch (Exception e)
{
_logger.Error(e);
throw;
}
}
,但出现异常:
输入“System.Collections.Generic.List`1[[MyClass, MyNameSpace,版本=1.0.0.0,文化=中性, PublicKeyToken=null]]' 带有数据合约名称 'ArrayOf*MyClass*:http://schemas.datacontract.org/2004/07/MyNameSpace' 预计不会。考虑使用 DataContractResolver 或添加任何 已知类型列表中静态未知的类型 - 例如, 通过使用 KnownTypeAttribute 属性或将它们添加到 传递给 DataContractSerializer 的已知类型列表。
[KnownType(typeof(MyClass))]
[DataContract]
public class MyClass
{
#region Properties
[DataMember]
public string Foo{ set; get; }
[DataMember]
public string Bar{ set; get; }
}
有什么想法吗?
没有继承权。
I have the following code in which I'm trying to serialize a list to a file
public static void Serialize<T>(this IList<T> list, string fileName)
{
try
{
var ds = new DataContractSerializer(typeof(T));
using (Stream s = File.Create(fileName))
ds.WriteObject(s, list);
}
catch (Exception e)
{
_logger.Error(e);
throw;
}
}
and I'm getting the exception:
Type 'System.Collections.Generic.List`1[[MyClass,
MyNameSpace, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]]' with data contract name
'ArrayOf*MyClass*:http://schemas.datacontract.org/2004/07/MyNameSpace'
is not expected. Consider using a DataContractResolver or add any
types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the
list of known types passed to DataContractSerializer.
[KnownType(typeof(MyClass))]
[DataContract]
public class MyClass
{
#region Properties
[DataMember]
public string Foo{ set; get; }
[DataMember]
public string Bar{ set; get; }
}
Any ideas?
There is no inheritance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
发生的情况是序列化器需要 T 的实例,而不是 T 的列表,因此您希望您的方法如下所示:
What has happened is that the serializer is expecting an instance of T, not a list of T, so you want your method to be like so:
正如建议的,序列化器应该用于列表,而不是项目的类型。
此外,
[KnownType(typeof(MyClass))]
应该在参数中采用继承自 MyClass 的类,而不是 MyClass 本身。As suggested, the serializer should be for the list, not the type of items.
Additionally,
[KnownType(typeof(MyClass))]
should take a class inheriting from MyClass in parameter, not MyClass itself.试试这个:
try this instead: