您可以:
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
的序列化。这样,您将序列化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 ;
var ins2 = new Instruction ;
byte[] bytes;
using (var ms = new MemoryStream())
Instruction ins3, ins4;
using (var ms = new MemoryStream(bytes))
如果
Operand
是一些不能直接序列化的东西,那么你可以在
GetObjectData
内创建它的替代品。
OpCode
正在使用本地资源? - Mark Segal