关于 MSDN他们写
Fields can be marked as optional by applying the OptionalFieldAttribute attribute to them. During deserialization, if the optional data is missing, the serialization engine ignores the absence and does not throw an exception.
我无法获得异常(exception)。我尝试创建一个类,用 SerializableAttribute 标记它,用 BinaryFormatter 序列化一个对象并将状态保存到磁盘上的文件,然后向我的类添加两个我没有用 OptionalFieldAttribute 标记的字段,并尝试反序列化反对我刚刚坚持到磁盘。我很惊讶没有抛出异常?
最佳答案
引用的 MSDN 页面没有提到这一点,但默认行为是在这种情况下不会抛出异常。如果需要异常,则必须将 BinaryFormatter
的 AssemblyFormat
属性设置为
System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full
默认值为
System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
可以找到更多信息 here .
关于c# - OptionalFieldAttribute 真的有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18579431/