IDeserializationCallback vs OnDeserializedAttribut

2020-07-02 12:29发布

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:

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

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?

4条回答
对你真心纯属浪费
2楼-- · 2020-07-02 12:48

Darren Headrick's post from above link (for completeness) :

DeserializationCallback.OnDeserialization "Runs when the entire object graph has been deserialized." (link).

The OnDeserialized event however "Use the OnDeserializedAttribute when you need to fix values on a deserialized object after it has been deserialized and before the graph is returned. This attribute can be used instead of the IDeserializationCallback interface." (link).

Since the OnDeserialized attribute can be used to modify the object graph, it gets called before OnDeserialization (which signifies the Object graph is in its final state).

查看更多
乱世女痞
3楼-- · 2020-07-02 12:52

Further discussion on this blog post

查看更多
不美不萌又怎样
4楼-- · 2020-07-02 12:55

Those two serve different purposes and cannot be used interchangeably. In most of the cases you probably will be better served by the interface.

Look here for some explanation: http://social.msdn.microsoft.com/Forums/en-US/netfxremoting/thread/311b2b57-6b0a-49ed-aa96-84f69d51da0f

查看更多
狗以群分
5楼-- · 2020-07-02 13:04

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.

查看更多
登录 后发表回答