我有一个反序列化方法(用 [OnDeserialized()]
属性装饰),我想在派生类中覆盖它。当我尝试这样做时,出现以下运行时错误:
An unhandled exception of type 'System.TypeLoadException'.... Type 'BaseObj' in assembly ... has method 'OnDeserialization' which is either static, virtual, abstract or generic, but is marked as being a serialization callback method.
我找不到任何文档来确认对序列化回调的这种限制(错误消息本身除外)。谁能解释一下这个奇怪的限制?
基于评论中的建议 here ,我求助于从 OnDeserialization 方法中调用一个单独的虚函数,如下所示:
[Serializable()]
public class BaseObj
{
protected string obj { get; set; }
[OnDeserialized()]
public void OnDeserializedMethod(StreamingContext context)
{
//call the virtual method because deserialization callbacks can’t be virtual
onDeserialized(context);
}
virtual protected void onDeserialized(StreamingContext context)
{
obj = "This value was deserialized by the base class.";
}
}
[Serializable()]
public class DerivedObj : BaseObj
{
override protected void onDeserialized(StreamingContext context)
{
obj = "This value was deserialized by the derived class.";
}
}
这似乎工作正常,但似乎相当“笨拙”。这真的是我唯一的选择吗?为什么序列化回调方法不能是虚拟的?
最佳答案
由于 BinaryFormatter
和 DataContractSerializer
在反序列化时不调用构造函数,OnDeserializedAttribute
允许执行通常在构造函数中执行的操作,例如状态初始化。由该属性标记的方法也按照与构造函数相同的顺序执行:首先是基础,然后是派生。
因此,为了反序列化的目的,您可以将这些方法视为构造函数。
和虚拟构造函数are not allowed in C# .
关于c# - 为什么序列化回调方法不能是虚拟的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45193452/