Reputation: 10981
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 attribute?
Is it possible?
Upvotes: 1
Views: 326
Reputation: 1062770
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:
Page
implementation and it doesn't matterPage
library (your dto can stay the same)Upvotes: 1
Reputation: 25810
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.
Upvotes: 0
Reputation: 39625
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 as tPage
and is marked as [Serializable]
. Copy the values from a tPage
instance to an instance of tSerializablePage
when you want to perform serialization and pass the tSerializablePage
to the serializer. When this instance is deserialized you will be responsible for creating an instance of tPage
from the values it contains.
Implement the ISerializationSurrogate
interface for tPage
, to provide a mechanism to directly serialize and deserialize tPage
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.
Upvotes: 6