【发布时间】:2013-05-07 22:29:21
【问题描述】:
在 C# 4.0 中,我尝试使用 DataContractSerializer 序列化和反序列化 Tuple<Guid, int[]>。我已经成功序列化和反序列化类型Guid、类型int[] 和类型Tuple<Guid, int>。如果我尝试序列化类型Tuple<Guid, int[]>,一切都会编译,但会出现以下运行时异常:
Type 'System.Int32[]' with data contract name
'ArrayOfint:http://schemas.microsoft.com/2003/10/Serialization/Arrays'
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.
我的序列化和反序列化例程很简单:
public static string Serialize<T>(this T obj)
{
var serializer = new DataContractSerializer(obj.GetType());
using (var writer = new StringWriter())
using (var stm = new XmlTextWriter(writer))
{
serializer.WriteObject(stm, obj);
return writer.ToString();
}
}
public static T Deserialize<T>(this string serialized)
{
var serializer = new DataContractSerializer(typeof(T));
using (var reader = new StringReader(serialized))
using (var stm = new XmlTextReader(reader))
{
return (T)serializer.ReadObject(stm);
}
}
为什么我会收到此异常,我可以做些什么来解决或绕过它?在我看来,包含可序列化类型的 Tuple 应该不会有序列化问题。
【问题讨论】:
-
您是否尝试过错误消息提示的任何操作?
-
我查看了 DataContractResolver,但我不确定如何以通常适用于 Tuples 中基本类型或集合类型的任意组合的方式使用它。到目前为止,我发现的所有示例都只使用了一个已知的预先存在的类。我需要它来为
Tuple<Guid, int[]>、Tuple<int[], int[]>、Tuple<int[], int>等以及具有 2 或 3 个项目/集合的元组工作,最好不用一堆案例来测试每个组合。
标签: c# c#-4.0 serialization tuples datacontractserializer