IDeserializationCallback与OnDeserializedAttribute [英] IDeserializationCallback vs OnDeserializedAttribute

查看:46
本文介绍了IDeserializationCallback与OnDeserializedAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,当对象反序列化后需要执行某些任务时,可以同时使用IDeserializationCallback接口和OnDeserialized事件.

As far as I understand, the IDeserializationCallback interface and the OnDeserialized event can both be used when an object needs to perform some task after being deserialized.

IDeserializationCallback:

IDeserializationCallback:

[Serializable]
public class Foo : IDeserializationCallback
{
    public void OnDeserialization(object sender)
    {
         // initialize unserialized fields etc.
    }
}

OnDeserialized事件:

OnDeserialized event:

[Serializable]
public class Foo
{
    [OnDeserialized]
    public void OnDeserialized(StreamingContext context)
    {
         // initialize unserialized fields etc.
    }
}

是否有任何特定的优缺点或场景供您选择?

Are there any specific pros/cons or scenarios where you would choose one over the other?

推荐答案

我想知道同样的事情.就优点/缺点而言,我只能说该接口具有优势,因为它迫使您实施正确的方法签名,因为属性版本将使您很高兴地编译类,而不管您的方法签名是什么样子

I have wondered the same thing. As far as pros/cons go, I can only reason that the interface has an advantage in that it forces you to implement the correct method signature where-as the attribute version will happily let you compile your class regardless of what your method signature looks like.

这篇关于IDeserializationCallback与OnDeserializedAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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