序列化'这个'

时间:2012-03-15 23:41:14

标签: c# .net serialization

好的,如果我有这样的课......

[serializable]
public class MyClass() : ISerializable
{
  public Dictionary<string, object> Values {get; set;}
}

我知道我要做什么来序列化它(对于那些试图找到快速答案的人来说,答案是这样的)......

protected MyClass(SerializationInfo info, StreamingContext context)
{
  Values = (Dictionary<string, object>)info.GetValue("values", typeof(Dictionary<string, object>));
}

public void GetObjectData(SerializationInfo info, StreamingContext context)
{
  info.AddValue("values", Values);
}

我的问题是,如果我想要定义一个继承自Dictionary的类,我该怎么办?

我到目前为止......

[serializable]
public class MyClass() : Dictionary<string, object>, ISerializable
{
  public void GetObjectData(SerializationInfo info, StreamingContext context)
  {
    info.AddValue("me", this);
  }
}

然后我迷路了。我不能写这个......

protected MyClass(SerializationInfo info, StreamingContext context)
{
  this = (MyClass)info.GetValue("me", typeof(MyClass));
}

&#39; cos&#39; this&#39;是r / o。那么,我该怎么办?我对GetObjectData()的实现是否正确?

我不相信它会有所作为,但为了防万一,我在.Net 4.0下写这篇文章

1 个答案:

答案 0 :(得分:6)

Dictionary<T, V>已实施ISerializable(请参阅this)。所以只需调用基类中的方法:

public class MyClass() : Dictionary<string, object>
{
      protected MyClass(SerializationInfo info, StreamingContext context) 
          : base(info, context) // Call the constructor in Dictionary
      {
         // instantiate other properties you had added to MyClass.
      }

      public void GetObjectData(SerializationInfo info, StreamingContext context)
      {
        base.GetObjectData(info, context); 
        // Now add other fields that MyClass implements.
        info.AddValue("whatever", this.AnotherProperty); 
      }
}