is it possible to extend class attribute in .net?
I have a library. This library contains class named tPage
. This tPage
class not marked serializable. I can't modify this library. I need to serialize this.
How to extend this class attri开发者_运维技巧bute?
Is it possible?
You cannot serialize that class if it's not marked [Serializable]
. If you inherit from it, and apply the attribute to your subclass, the serializer will throw an exception because it cannot serialize the base class members.
There are two practical ways around this problem:
Create a new class
tSerializablePage
which contains the same data astPage
and is marked as[Serializable]
. Copy the values from atPage
instance to an instance oftSerializablePage
when you want to perform serialization and pass thetSerializablePage
to the serializer. When this instance is deserialized you will be responsible for creating an instance oftPage
from the values it contains.Implement the
ISerializationSurrogate
interface fortPage
, to provide a mechanism to directly serialize and deserializetPage
instances.
If you aren't familiar with manual serialization interfaces, the former solution may be easier for you to implement, however the interface is .NET Framework solution to the problem of serializing a non-serializable class.
I'm making the assumption that you are using BinaryFormatter
. First, I'd argue that BinaryFormatter
is not always a good idea (it is very brittle, and doesn't withstand much change). But I'd also suggest that the problem is that you are trying to serialize the implementation, when in fact all you need to serialize is the data.
I would approach this problem by writing my own DTO that represents the state of the system, and serialize the DTO:
PageDto tmp = new PageDto(myPageInstance);
// serialize tmp
Advantages:
- you know what data (state) you are serializing
- it is implementation unaware; you can use a different
Page
implementation and it doesn't matter - you can use your choice of serializers by using the appropriate attributes etc
- it doesn't break serialization when you update your version of the
Page
library (your dto can stay the same)
It is not serializable probably due to the internals of the class (e.g. some members cannot be serialized). So if you can dissect/reverse engineer the class and make it safe for serialization, go ahead. Else, 'hacking' after inherting will not work for you.
Programming Hero
made good suggestions (saw it while typing my answer). You might want to give his ideas some thoughts.
精彩评论