Dynamic Object Serialization

前端 未结 4 1074
北海茫月
北海茫月 2020-12-05 05:09

I tried to serialize a DynamicObject class with BinaryFormatter, but:

  • Output file is too big, not exactly wire-friendly
  • Circ
4条回答
  •  难免孤独
    2020-12-05 05:36

    I'm 98% certain that this sequence will work for a dynamic object.

    1. convert object to an Expando Object
    2. cast expando object to be of type Dictionary
    3. use ProtoBuf-net Serializer.Serialize / .Deserialize as per normal
    4. convert dictionary to Expando Object

    You can convert objects to a collection of name/value pairs for transfering.

    That's just a small subset of what dynamic can do, but perhaps it is enough for you.

    There's some custom code to handle some of the conversions above that I can show you if there's interest.

    I don't have a solution for when dynamic is a placeholder to a class. For this case I'd suggest getting the type and using a switch statement to serialize / deserialize as you require. For this last case, you'd need to place a something to indicate which type of generic deserialization that you need (string / id / fully qualified type name / etc). Assumption is that you are dealing with a list of expected types.

    Note: Expando implements IDictionary. An Expando is merely merely a list of key/value pairs. ie. the thing you dot into is the key, and the value is the return from whatever chain of functions implements that. There are a set of dynamic interfaces for customising the syntactic sugar experience, but most of the time you wont to look at them.

    refs:

    • Dictionary from IDictionary using the constructor -- http://msdn.microsoft.com/en-us/library/et0ke8sz(v=vs.110).aspx
    • IDictionary/Dictionary to Expando -- http://theburningmonk.com/2011/05/idictionarystring-object-to-expandoobject-extension-method/

提交回复
热议问题