简体   繁体   中英

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 attribute?

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 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.

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM