使用Protocol Buffers的序列化哈希表(.NET) [英] Serialize hashtable using Protocol Buffers (.NET)
问题描述
我想序列化/反序列化,其中包含使用protobuf网v2的散列表属性我的自定义类。
I am trying to serialize/deserialize my custom class which contains hashtable property using protobuf-net v2.
[ProtoContract]
public class MyClass
{
[ProtoMember(1)]
public Hashtable MyHashTable { get; set; }
}
当我打电话出现Serializer.Serialize(...)异常: 没有的类型定义的串行:的System.Collections.Hashtable 的
When I call Serializer.Serialize(...) exception appears: No serializer defined for type: System.Collections.Hashtable
我试着修改:
[ProtoContract]
public class MyClass
{
[ProtoMember(1, DynamicType = true)]
public Hashtable MyHashTable { get; set; }
}
不过,我还有一个例外: 类型未预期,并没有合同可以推断出:System.Collections.DictionaryEntry 的
But I have another exception: Type is not expected, and no contract can be inferred: System.Collections.DictionaryEntry
也许有人知道的方式我怎么可以序列化哈希表?
Maybe someone know a way how I can serialize hashtable?
推荐答案
感谢所有谁帮我。下面是我的解决方案。我知道这是不是最好的办法,但也许有人可以接受。
Thanks to all who helped me. Here is my solution. I know that this is not best way, but maybe for someone it acceptable.
[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());
}
}
这篇关于使用Protocol Buffers的序列化哈希表(.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!