WEB开发网
开发学院软件开发C语言 Effective C# 原则25: 让你的类型支持序列化 阅读

Effective C# 原则25: 让你的类型支持序列化

 2009-02-19 08:16:24 来源:WEB开发网   
核心提示: private MyType( SerializationInfo info,StreamingContext cntxt );下面的序列化构造函数演示了如何从先前的版本中读取数据,以及和默认添加的Serializable特性生成的序列化保持供一致,Effective C# 原则25: 让

private MyType( SerializationInfo info,
 StreamingContext cntxt );

下面的序列化构造函数演示了如何从先前的版本中读取数据,以及和默认添加的Serializable特性生成的序列化保持供一致,来读取当前版本中的数据:

using System.Runtime.Serialization;
using System.Security.Permissions;
[Serializable]
public sealed class MyType : ISerializable
{
 private string _label;
 [NonSerialized]
 private int _value;
 private OtherClass _object;
 private const int DEFAULT_VALUE = 5;
 private int _value2;
 // public constructors elided.
 // Private constructor used only by the Serialization
    framework.
 private MyType( SerializationInfo info,
  StreamingContext cntxt )
 {
  _label = info.GetString( "_label" );
  _object = ( OtherClass )info.GetValue( "_object", typeof
   ( OtherClass ));
  try {
   _value2 = info.GetInt32( "_value2" );
  } catch ( SerializationException e )
  {
   // Found version 1.
   _value2 = DEFAULT_VALUE;
  }
 }
 [SecurityPermissionAttribute(SecurityAction.Demand,
  SerializationFormatter =true)]
 void ISerializable.GetObjectData (SerializationInfo inf,
  StreamingContext cxt)
 {
  inf.AddValue( "_label", _label );
  inf.AddValue( "_object", _object );
  inf.AddValue( "_value2", _value2 );
 }
}

上一页  1 2 3 4 5 6  下一页

Tags:Effective 原则 类型

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接