[英]What happens to fields you mark [NonSerialized] when you deserialize?
Are these fields set to default values like when a new instance is created? 这些字段是否设置为默认值(例如在创建新实例时)? Can I create custom code to set these fields to new values upon deserialization?
我可以创建自定义代码以在反序列化时将这些字段设置为新值吗?
Note: all of this is specific to BinaryFormatter
: 注意:所有这些都是特定于
BinaryFormatter
:
By default, they are ignored completely; 默认情况下,它们将被完全忽略。 they will have their type-default values, ie a zero-value / null-value.
它们将具有其类型默认值,即零值/空值。
If you implement custom serialization ( ISerializable
), then [NonSerializable]
doesn't apply, and you can do what you want, but most people don't want to have to do this. 如果实现自定义序列化(
ISerializable
),则[NonSerializable]
不适用,您可以执行所需的操作,但是大多数人都不想这样做。 However, you can also implement IDeserializationCallback
, which provides an ideal opportunity to initialize such fields: 但是,您也可以实现
IDeserializationCallback
,它提供了初始化此类字段的理想机会:
[Serializable]
class Foo : IDeserializationCallback
{
// ... not shown
void IDeserializationCallback.OnDeserialization(object sender)
{
// init your [NonSerialized] fields here
}
}
Note that other serializers have different implementations for serialization callbacks, some of which are also supported by BinaryFormatter
, for example: 请注意,其他序列化程序对序列化回调具有不同的实现,例如
BinaryFormatter
也支持其中一些:
[Serializable]
class Foo
{
// ... not shown
[OnDeserializing]
private void AnyMethodName(StreamingContext c)
{
// init your [NonSerialized] fields here
}
}
The attribute-based callbacks provide more opportunities to inject code at specific points, and are usually preferred. 基于属性的回调提供了更多在特定点插入代码的机会,通常是首选。 There are 4:
[OnDeserializing]
, [OnDeserialized]
, [OnSerializing]
and [OnSerialized]
. 有4个:
[OnDeserializing]
, [OnDeserialized]
, [OnSerializing]
和[OnSerialized]
。
When a new instance is creted this fields are default value of type. 创建新实例时,此字段是type的默认值。
You can set set your custom values on object construct 您可以在对象构造上设置设置自定义值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.