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 を見ましたが、そのようなコンテキストでそれを使用する方法がよくわかりません (リポジトリから正しいバージョンを選択したかどうかさえわかりませんが、ねえ)。
言葉というよりはコードだとは思いますが、シナリオをこれ以上うまく説明できるとは思いません。この質問をより明確にするために追加できるものがあるかどうか教えてください。
どんな助けでも大歓迎です。