你可以:
public class Instruction
{
public OpCode Op { get; set; }
public string OpString
{
get
{
return Op.Name;
}
set
{
Op = (OpCode)typeof(OpCodes).GetField(value, BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase).GetValue(null);
}
}
public object Operand { get; set; }
}
并禁用Op 的序列化。这样你就可以序列化操作码的Name(一个string),然后你就可以反序列化它了。
使用BinaryFormatter,您可以使用ISerializable 接口并手动序列化:
[Serializable]
public class Instruction : ISerializable
{
public OpCode Op { get; set; }
public object Operand { get; set; }
public Instruction()
{
}
public Instruction(SerializationInfo info, StreamingContext context)
{
Op = (OpCode)typeof(OpCodes).GetField(info.GetString("Op"), BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase).GetValue(null);
Operand = info.GetValue("Operand", typeof(object));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Op", Op.Name);
info.AddValue("Operand", Operand);
}
}
使用示例:
var ins1 = new Instruction { Op = OpCodes.Add, Operand = (short)5 };
var ins2 = new Instruction { Op = OpCodes.Sub, Operand = 5.0 };
byte[] bytes;
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, ins1);
bf.Serialize(ms, ins2);
bytes = ms.ToArray();
}
Instruction ins3, ins4;
using (var ms = new MemoryStream(bytes))
{
var bf = new BinaryFormatter();
ins3 = (Instruction)bf.Deserialize(ms);
ins4 = (Instruction)bf.Deserialize(ms);
}
如果Operand 可以是不能直接序列化的东西,那么您可以在GetObjectData 中创建它的代理项。