I've been doing some reading on serialization in .NET and started wondering what was the main reason of implementing the OnSerializing/OnSerialized/OnDeserializing/OnDeserialized functionality as attributes in contrast to an interface. I can think of some pros and cons but I'm probably missing something crucial so I wanted to know what outweighed.
In favor of an interface:
Method signatures are checked at compile time (using an attribute on a method with an incorrect signature causes a runtime exception)
No two methods could be declared for a single event 开发者_开发知识库on a class level (decorating two methods with the same attribute causes a runtime exception)
In favor of attributes:
- No need to declare 4 methods if we want to react to a single event
An interface would not be as good because there is then no automatic way for each class in a hierarchy on top of the interface to provide its own implementation unless:
- The base class declares the methods as virtual
- Each deriving class re-implements the interface
Then there is the added complication of identifying each class's implementation - the reflection is harder.
Furthermore, once the interface is brought in, the implication is that all classes in a hierarchy are serializable, but this is not always, nor should it always, be the case. It is entirely proper to derive a non serializable class from a serializable base (in controlled circumstances) - but this is effectively prevented through the use of either interfaces or virtual methods.
The use of attributes, then, provide the tersest, most expressive and actually most flexible way to implement serialization.
Here's another reason in favor of attributed methods over an interface.
If an interface were used, it would be possible for a subclass to override the method implementation, hiding the base class's implementation. Of course, the subclass's implementation would have a responsibility to explicitly invoke the overridden method, but it's usually a bad idea to make proper program behavior contingent upon programmer responsibility.
The way things are implemented now, a subclass's serialization triggered method will not hide the base class's. The serialization framework is responsible for making sure they all get called in proper order, and the serialization framework is trustworthy.
Because the implementation can be partial. If all those method reside in the same interface you have 4 methods that you maybe dont need but you have to provide an implementation for them. On the other hand you could have one interface for each method but then you have 4 interfaces that you sometimes need to implement. That's a lot of methods and interfaces that can be avoided in this way.
精彩评论