我试图序列化DynamicObject
类BinaryFormatter
,但:动态对象序列化
- 输出文件太大,不完全丝友好
- 循环引用不处理(停留在序列化)
由于序列化一个DynamicObject
意味着自己很少,这里是我试图序列化的类:
[Serializable()]
class Entity
: DynamicObject, ISerializable
{
IDictionary<string, object> values = new Dictionary<string, object>();
public Entity()
{
}
protected Entity(SerializationInfo info, StreamingContext ctx)
{
string fieldName = string.Empty;
object fieldValue = null;
foreach (var field in info)
{
fieldName = field.Name;
fieldValue = field.Value;
if (string.IsNullOrWhiteSpace(fieldName))
continue;
if (fieldValue == null)
continue;
this.values.Add(fieldName, fieldValue);
}
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
this.values.TryGetValue(binder.Name, out result);
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
this.values[binder.Name] = value;
return true;
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (var kvp in this.values)
{
info.AddValue(kvp.Key, kvp.Value);
}
}
}
(我想我可以用一个ExpandoObject,但那是另一回事。)
这里有一个简单的测试程序:
static void Main(string[] args)
{
BinaryFormatter binFmt = new BinaryFormatter();
dynamic obj = new Entity();
dynamic subObj = new Entity();
dynamic obj2 = null;
obj.Value = 100;
obj.Dictionary = new Dictionary<string, int>() { { "la la la", 1000 } };
subObj.Value = 200;
subObj.Name = "SubObject";
obj.Child = subObj;
using (var stream = new FileStream("test.txt", FileMode.OpenOrCreate))
{
binFmt.Serialize(stream, obj);
}
using (var stream = new FileStream("test.txt", FileMode.Open))
{
try
{
obj2 = binFmt.Deserialize(stream);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Console.ReadLine();
}
把一些断点在这里和那里帮我看看在obj2的内容,它看起来像原始数据正确反序列化,但有上述缺点,如果你有想象力和移动数据。
我看了一下Marc Gravell的protobuf-net,但我不确定如何在这样的环境下使用它(我甚至不确定我是否从版本库中选择了正确的版本,但是嘿) 。
我知道它比单词更多的代码,但我不认为我可以更好地解释这种情况。请告诉我是否可以添加一些内容以使问题更清楚。
任何帮助,非常感谢。
作为参考,* protobuf网*目前有没有支持'dynamic'。我建议移动到DTO层进行序列化。 – 2010-06-16 20:30:19
@Marc - 谢谢,我会研究一下。仍然接受其他建议。 – Raine 2010-06-17 08:19:23
好吧,长期来说,这是我计划在protobuf网支持的东西。但我目前无法承诺。 – 2010-06-17 09:50:59