我正在尝试将 HashSet 序列化为以下代码。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace ConsoleApplication20
{
class Program
{
static void Main(string[] args)
{
var sr = new DataContractSerializer(typeof(Test));
var t = new Test();
var mem = new MemoryStream();
sr.WriteObject(mem, t);
}
}
[DataContract]
public class Test
{
[DataMember]
public ISet<int> TestSet = new HashSet<int>();
}
}
但是这段代码失败了:
输入“System.Collections.Generic.HashSet`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]”,数据协定名称为“ArrayOfint: http://schemas.microsoft.com/2003/10/Serialization/Arrays”预计不会。考虑使用 DataContractResolver 或将任何静态未知的类型添加到已知类型列表
我绝对不想碰这一行:
public ISet<int> TestSet = new HashSet<int>();
除此之外,由于某些其他原因(该类型实际上不是哈希集),在这种情况下,我不允许 HashSet 作为已知类型。 我应该怎么办 ?
最佳答案
我不确定为什么会出现异常,因为将 TestSet 更改为其他类型(如 IEnumerable<int>
)不会导致异常。但添加
[KnownType(typeof(HashSet<int>))]
到你的类(class)解决你的问题。
[DataContract]
[KnownType(typeof(HashSet<int>))]
public class Test
{
[DataMember]
public ISet<int> TestSet = new HashSet<int>();
}
另请参阅 post了解更多信息。
关于.net - HashSet 的 DataContract 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15495903/