开发者

How to make a class serializable without Serializable attibute in .net

开发者 https://www.devze.com 2022-12-23 18:32 出处:网络
I have one debugger visualizer for seeing list of class object in the form of data table. But the limitation for the code is that the class should be seria开发者_如何学编程lizable i.e. should be marke

I have one debugger visualizer for seeing list of class object in the form of data table. But the limitation for the code is that the class should be seria开发者_如何学编程lizable i.e. should be marked as [Serializable] and if the class is not marked Serializable then the debugger crashes. So, can anybody tell me how to make a class Serializable at run time if the class is not marked Serializable.


You cannot modify the metadata of an existing class at runtime.


If a class is not marked [Serializable], you can try serialization using SerializationSurrogate


Any class with public get/set properties is XmlSerializable. Can you use XML serializers instead ?


The fact that a class is missing [Serializable] can be explained two ways. It might be an error of omission, the more common case. Or the class can simply not support serialization. Which is not unusual, classes often depend on state that cannot be faithfully reproduced at deserialization time because it depends on global program state. Any of the Windows Forms controls would be a good example, they can't be deserialized without having a native Windows window that is in the required state, a state that often requires other windows to be created as well (like the container window) and many messages.

Well, this isn't going to help you implement your visualizer. You can't reliably implement it with serialization. Using reflection however gives you access to the same property and field values. And reflection is always supported.


You could look at your question differently, using [Serializable] allows you to use the dotnet libraries to serialize into json, xml etc. You can still serialize by writing your own methods to do so as fundamentally just about any data structure can be represented in xml or json format.

Adding [Serializable] to classes is one of the best practice tips in Bill Wagner's brilliant book Effective C#: 50 specific ways to improve your C#.

You can serialize a class without it being [Serializable] as @Darin (+1) pointed out you can't retrospectively redecorate a class. If I were you I'd put in [Serializable] as working around this is not worth the effort.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号