How to extend a serializable class so that it can still be serializable?

I have a class that I want to save in the ViewState for asp.net UserControl. It basically extends the general list in several ways, but also adds some properties, for example.

public class MyListClass: List<MyObject> { public string ExtraData; // some public methods } 

MyObject is serializable, with methods implemented as follows:

 [Serializable()] class MyObject { public MyObject(SerializationInfo info, StreamingContext ctxt) { Prop1 = (string)info.GetValue("Prop1", typeof(string)); //... } public void GetObjectData(SerializationInfo info, StreamingContext ctxt) { info.AddValue("Prop1",Prop1); } } 

And general lists are essentially serializable. ViewState works fine with List<MyObject> , but I can't figure out how to implement serialization for MyListClass.

Intuitively, what I want to do is something like this:

 public MyListClass(SerializationInfo info, StreamingContext ctxt) { ExtraData= (string)info.GetValue("ExtraData", typeof(string)); this = (List<MyClass>)info.GetValues("BaseList",typeof(List<MyClass>)); } 

Obviously this will not work. What is the right way to do this?

+4
source share
2 answers

You can simply put the Serializable tag in MyListClass, which will serialize ExtraData as its own field.

+3
source

See the documentation in the PageStatePersister Class for how ASP.NET handles ViewState these days. In particular, see the ObjectStateFormatter Class , which is the default implementation of IStateFormatter .

From this documentation, it seems that any class that can be serialized using BinaryFormatter should work.

0
source

Source: https://habr.com/ru/post/1332968/


All Articles