序列化'这个'

Stu*_*ing 1 .net c# serialization

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

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

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

但后来我迷路了.我写不出来......

protected MyClass(SerializationInfo info, StreamingContext context)
{
  this = (MyClass)info.GetValue("me", typeof(MyClass));
}
Run Code Online (Sandbox Code Playgroud)

'cos'这个'是r/o.那么,我该怎么办?我对GetObjectData()的实现是否正确?

我不相信它会有所作为,但万一它确实如此,我在.Net 4.0下写这个

Die*_*ego 6

Dictionary<T, V>已经实现了ISerializable(见).所以只需调用基类中的方法:

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); 
      }
}
Run Code Online (Sandbox Code Playgroud)