c# - OptionalFieldAttribute 真的有效吗?

标签 c# serialization

关于 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 页面没有提到这一点,但默认行为是在这种情况下不会抛出异常。如果需要异常,则必须将 BinaryFormatterAssemblyFormat 属性设置为

System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full

默认值为

System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple

可以找到更多信息 here .

关于c# - OptionalFieldAttribute 真的有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18579431/

相关文章:

c# - C#中对象的内存地址

c# - 从队列触发器启动 Azure 辅助角色

c++ - 如何实现double的序列化和反序列化?

android - 在 Android 应用程序中使用 Json 解析进行 JSON 反序列化

c# - 我真的需要写这个 "SerializationHelper"吗?

c# - 如何在Windows中使用C#更改扬声器配置?

c# - 如何根据一列获取数据库中的整行

c# - 将字符串转换为 DateTime 对象并将其添加到总时间

asp.net - 如何序列化 LINQ-to-SQL 惰性列表

c++ - 在 C++ 中使用指针序列化一个类