This article describes the implementation method of C# custom serialization ISerializable. Share it for your reference. The specific implementation method is as follows:
[Serializable] public class BaseObject { [OptionalField] private string _str = "I am BaseObject"; } [Serializable] public class TestObject : BaseObject, ISerializable { int a; string strName = ""; Color c = ; DataTable _dtColors = null; [OptionalField] ArrayList list = new ArrayList(); [OptionalField] List<int> list1 = new List<int>(); [OptionalField] Dictionary<int, string> dic = new Dictionary<int, string>(); //When implementing the ISerializable interface, if the constructor does not exist, a SerializationException will be raised //This feature indicates that this method only allows the serializer to be tuned [SecurityPermissionAttribute(, SerializationFormatter = true)] protected TestObject(SerializationInfo info, StreamingContext context) { #region If the base class also implements the ISerializable interface, the serializer will automatically call the constructor of the base class, and this code is not required. Type basetype = ().BaseType; MemberInfo[] mi = (basetype, context); for (int i = 0; i < ; i++) { // Since AddValue cannot add a duplicate value, in order to avoid the subclass variable name being the same as the base class variable name, add the base class name to the serialized variable name of the base class name to the base class name in order to avoid the subclass variable name being the same as the base class variable name. FieldInfo fi = (FieldInfo)mi[0]; object objValue = ( + "+" + , ); (this, objValue); } #endregion a = info.GetInt32("a"); strName = ("strName"); c = (Color)("c", typeof(Color)); _dtColors = (DataTable)("_dtColors", typeof(DataTable)); list = (ArrayList)("list", typeof(ArrayList)); list1 = (List<int>)("list1", typeof(List<int>)); dic = (Dictionary<int, string>)("dic", typeof(Dictionary<int, string>)); } public TestObject() { a = 100; strName = "daps"; InitColorTable(); (10); (20); } #region ISerializable Member [SecurityPermissionAttribute(, SerializationFormatter =true)] void (SerializationInfo info, StreamingContext context) { ("a", a); ("strName", strName); ("c", c); ("_dtColors", _dtColors); ("list", list); ("list1", list1); ("dic", dic); Type basetype = ().BaseType; MemberInfo[] mi = (basetype, context); for (int i = 0; i < ; i++) { // Since AddValue cannot add a duplicate value, in order to avoid the subclass variable name being the same as the base class variable name, add the base class name to the serialized variable name of the base class name to the base class name in order to avoid the subclass variable name being the same as the base class variable name. ( + "+" + mi[i].Name, ((FieldInfo)mi[i]).GetValue(this)); } } #endregion }
I hope this article will be helpful to everyone's C# programming.