在.NET中,处理序列化的全局变量需要考虑以下几点:
ISerializable
接口,并重写GetObjectData
和ResolveUninitializedObject
方法。[Serializable]
public class GlobalVariable : ISerializable
{
public int Value { get; set; }
protected GlobalVariable() { }
public GlobalVariable(SerializationInfo info, StreamingContext context)
{
Value = info.GetInt32("Value");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Value", Value);
}
public static GlobalVariable ResolveUninitializedObject(StreamingContext context)
{
return new GlobalVariable();
}
}
BinaryFormatter
类将对象序列化为字节数组或字符串。GlobalVariable globalVar = new GlobalVariable { Value = 42 };
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, globalVar);
byte[] serializedData = ms.ToArray();
}
BinaryFormatter
类将字节数组或字符串反序列化为对象。byte[] serializedData = ...; // 从文件、网络等来源获取序列化数据
using (MemoryStream ms = new MemoryStream(serializedData))
{
BinaryFormatter formatter = new BinaryFormatter();
GlobalVariable globalVar = (GlobalVariable)formatter.Deserialize(ms);
}
注意:BinaryFormatter
已被认为是不安全的,因为它可能导致反序列化攻击。在实际项目中,建议使用其他序列化库,如Json.NET
、ProtoBuf
或MessagePack
。