閱讀目錄
spa
一:C#中泛型在方法Method上的實現code
把Persion類型序列化爲XML格式的字符串,把Book類型序列化爲XML格式的字符串,可是隻寫一份代碼,而不是public static string GetSerializeredString(Book book)這個方法寫一份,再public static string GetSerializeredString(Persion persion)再寫一份方法,而是在方法的調用時候再給他傳數據類型的類型
xml
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 using System.Xml.Serialization; 8 9 namespace GenericMethod2 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 Book book = new Book(); 16 book.BookNumber = "001"; 17 book.Name = "《西遊記》"; 18 19 Person person = new Person(); 20 person.PersonName = "張三"; 21 22 string bookXMLString = GetSerializeredString<Book>(book); 23 24 string personXMLString = GetSerializeredString<Person>(person); 25 26 Console.WriteLine(bookXMLString); 27 28 Console.WriteLine("--------------"); 29 30 Console.WriteLine(personXMLString); 31 Console.ReadLine(); 32 } 33 34 /// <summary> 35 /// 根據對象和泛型獲得序列化後的字符串 36 /// </summary> 37 /// <typeparam name="T"></typeparam> 38 /// <param name="t"></param> 39 /// <returns></returns> 40 public static string GetSerializeredString<T>(T t) 41 { 42 //1.step 序列化爲字符串 43 XmlSerializer xmlserializer = new XmlSerializer(typeof(T)); 44 MemoryStream ms = new MemoryStream(); 45 xmlserializer.Serialize(ms, t); 46 string xmlString = Encoding.UTF8.GetString(ms.ToArray()); 47 48 return xmlString; 49 } 50 51 } 52 53 [Serializable()] 54 [XmlRoot] 55 public class Book 56 { 57 string _booknumber = ""; 58 [XmlElement] 59 public string BookNumber 60 { 61 get { return _booknumber; } 62 set { _booknumber = value; } 63 } 64 65 string _name = ""; 66 [XmlElement] 67 public string Name 68 { 69 get { return _name; } 70 set { _name = value; } 71 } 72 } 73 74 [Serializable()] 75 [XmlRoot] 76 public class Person 77 { 78 string _personName = ""; 79 [XmlElement] 80 public string PersonName 81 { 82 get { return _personName; } 83 set { _personName = value; } 84 } 85 } 86 87 }