在 C# 4.0 中,我正在尝试Tuple<Guid, int[]>
使用 DataContractSerializer 序列化和反序列化。我已经成功地序列化和反序列化了 type Guid
、 typeint[]
和 type Tuple<Guid, int>
。如果我尝试序列化 type 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
,可以序列化的包含类型应该没有问题被序列化。