.net - HashSet 的 DataContract 序列化

标签 .net serialization hashset

我正在尝试将 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/

相关文章:

c# - 退出时杀死进程

c# - 重用 SqlConnection 的最佳实践

.net - 您尝试执行不包含指定表达式的查询错误

c# - 使用 DataContractJsonSerializer 创建非 XML Json 文件

java - 在 Gson 中,如何在反序列化期间检测类型不匹配?

java - 获取输入到 HashSet 后的数据读取顺序

java - HashSet<List<T>> 中的唯一条目,其中列表可能包含空条目

.net - 基于角色的导航项

java - 反序列化已知父类(super class)的随机派生类

java - HashSet对数组内容不敏感?