1

我正在尝试使用 protobuf-net v2 序列化/反序列化包含哈希表属性的自定义类。

    [ProtoContract]
    public class MyClass
    {
        [ProtoMember(1)]
        public Hashtable MyHashTable { get; set; }
   }

当我调用 Serializer.Serialize(...) 时出现异常: No serializer defined for type: System.Collections.Hashtable

我尝试修改:

    [ProtoContract]
    public class MyClass
    {
        [ProtoMember(1, DynamicType = true)]
        public Hashtable MyHashTable { get; set; }
   }

但我有另一个例外: 类型不是预期的,并且无法推断出任何合同:System.Collections.DictionaryEntry

也许有人知道我如何序列化哈希表?

4

1 回答 1

1

感谢所有帮助过我的人。这是我的解决方案。我知道这不是最好的方法,但也许有人可以接受。

    [ProtoContract]
    public class HashtableTestClass
    {
        private string inputParametersBase64 = string.Empty;
        private Hashtable myHashTable;

        public Hashtable MyHashtable
        {
            get { return myHashTable; }
            set { myHashTable = value; }
        }

        [ProtoMember(1)]
        public string InputParametersBase64
        {
            get
            {
                if (myHashTable == null)
                    return string.Empty;

                return HashtableToBase64(myHashTable);
            }
            set
            {
                inputParametersBase64 = value;
                if (!string.IsNullOrEmpty(inputParametersBase64))
                {
                    try
                    {
                        myHashTable = Base64ToHashtable(inputParametersBase64);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }
        }

        public static Hashtable Base64ToHashtable(string s)
        {
            MemoryStream stream = new MemoryStream(Convert.FromBase64String(s), false);
            IFormatter formatter = new BinaryFormatter();

            return (Hashtable)formatter.Deserialize(stream);
        }

        public static string HashtableToBase64(Hashtable hashtable)
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            formatter.Serialize(stream, hashtable);
            stream.Close();
            return Convert.ToBase64String(stream.ToArray());
        }
    }
于 2012-05-18T14:00:40.063 回答