C#自界說序列化ISerializable的完成辦法。本站提示廣大學習愛好者:(C#自界說序列化ISerializable的完成辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#自界說序列化ISerializable的完成辦法正文
本文實例講述了C#自界說序列化ISerializable的完成辦法。分享給年夜家供年夜家參考。詳細完成辦法以下:
[Serializable] public class BaseObject { [OptionalField] private string _str = "I am BaseObject"; } [Serializable] public class TestObject : BaseObject, ISerializable { int a; string strName = ""; Color c = Color.Red; DataTable _dtColors = null; [OptionalField] ArrayList list = new ArrayList(); [OptionalField] List<int> list1 = new List<int>(); [OptionalField] Dictionary<int, string> dic = new Dictionary<int, string>(); //當完成ISerializable接口時,假如該結構函數不存在,則會激發一個SerializationException異常 //該特征表現,該辦法只許可序列化器調 [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] protected TestObject(SerializationInfo info, StreamingContext context) { #region 假如基類也完成了ISerializable接口,則序列化器會主動挪用基類的該結構函數,就不須要本段代碼 Type basetype = this.GetType().BaseType; MemberInfo[] mi = FormatterServices.GetSerializableMembers(basetype, context); for (int i = 0; i < mi.Length; i++) { //因為AddValue不克不及添減輕名值,為了不子類變量名與基類變量名雷同,將基類序列化的變量名加上基類類名 FieldInfo fi = (FieldInfo)mi[0]; object objValue = info.GetValue(basetype.FullName + "+" + fi.Name, fi.FieldType); fi.SetValue(this, objValue); } #endregion a = info.GetInt32("a"); strName = info.GetString("strName"); c = (Color)info.GetValue("c", typeof(Color)); _dtColors = (DataTable)info.GetValue("_dtColors", typeof(DataTable)); list = (ArrayList)info.GetValue("list", typeof(ArrayList)); list1 = (List<int>)info.GetValue("list1", typeof(List<int>)); dic = (Dictionary<int, string>)info.GetValue("dic", typeof(Dictionary<int, string>)); } public TestObject() { a = 100; strName = "daps"; InitColorTable(); list1.Add(10); list1.Add(20); } #region ISerializable 成員 [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter =true)] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("a", a); info.AddValue("strName", strName); info.AddValue("c", c); info.AddValue("_dtColors", _dtColors); info.AddValue("list", list); info.AddValue("list1", list1); info.AddValue("dic", dic); Type basetype = this.GetType().BaseType; MemberInfo[] mi = FormatterServices.GetSerializableMembers(basetype, context); for (int i = 0; i < mi.Length; i++) { //因為AddValue不克不及添減輕名值,為了不子類變量名與基類變量名雷同,將基類序列化的變量名加上基類類名 info.AddValue(basetype.FullName + "+" + mi[i].Name, ((FieldInfo)mi[i]).GetValue(this)); } } #endregion }
願望本文所述對年夜家的C#法式設計有所贊助。