发生在你身上大关[非序列化]当您反序列化领域是什么? [英] What happens to fields you mark [NonSerialized] when you deserialize?

查看:146
本文介绍了发生在你身上大关[非序列化]当您反序列化领域是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是这些字段设置为默认创建一个新的实例时,像值?我可以创建自定义代码在反序列化到这些字段设置为新的价值?

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?

推荐答案

请注意:这一切是特定于的BinaryFormatter

Note: all of this is specific to BinaryFormatter:

在默认情况下,他们完全忽略;他们将有自己的类型的默认值,即零值/空值。

By default, they are ignored completely; they will have their type-default values, i.e. a zero-value / null-value.

如果您实现自定义序列化( ISerializable的),那么 [非序列化] 不适用,你可以做你想做的,但大多数人的不要的不得不这样做。但是,您也可以实现 IDeserializationCallback ,它提供了一个理想的机会来初始化这样的字段:

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. However, you can also implement IDeserializationCallback, which provides an ideal opportunity to initialize such fields:

[Serializable]
class Foo : IDeserializationCallback
{
    // ... not shown
    void IDeserializationCallback.OnDeserialization(object sender)
    {
        // init your [NonSerialized] fields here
    }
}

注意,其他串行器具有的不同的的序列化回调实现,其中一些的的由的BinaryFormatter ,例如

Note that other serializers have different implementations for serialization callbacks, some of which are also supported by BinaryFormatter, for example:

[Serializable]
class Foo
{
    // ... not shown
    [OnDeserializing]
    private void AnyMethodName(StreamingContext c)
    {
        // init your [NonSerialized] fields here
    }
}

基于属性的回调提供了更多的机会,在注入特定点的代码,通常首选。有4个: [OnDeserializing] [OnDeserialized] [OnSerializing] [OnSerialized]

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].

这篇关于发生在你身上大关[非序列化]当您反序列化领域是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆