2.C#中泛型在方法Method上的实现

时间:2021-03-13 23:00:14
  • 阅读目录

        一:C#中泛型在方法Method上的实现

        把Persion类型序列化为XML格式的字符串,把Book类型序列化为XML格式的字符串,但是只写一份代码,而不是public static string GetSerializeredString(Book book)这个方法写一份,再public static string GetSerializeredString(Persion persion)再写一份方法,而是在方法的调用时候再给他传数据类型的类型

     using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Serialization; namespace GenericMethod2
    {
    class Program
    {
    static void Main(string[] args)
    {
    Book book = new Book();
    book.BookNumber = "";
    book.Name = "《西游记》"; Person person = new Person();
    person.PersonName = "张三"; string bookXMLString = GetSerializeredString<Book>(book); string personXMLString = GetSerializeredString<Person>(person); Console.WriteLine(bookXMLString); Console.WriteLine("--------------"); Console.WriteLine(personXMLString);
    Console.ReadLine();
    } /// <summary>
    /// 根据对象和泛型得到序列化后的字符串
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="t"></param>
    /// <returns></returns>
    public static string GetSerializeredString<T>(T t)
    {
    //1.step 序列化为字符串
    XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
    MemoryStream ms = new MemoryStream();
    xmlserializer.Serialize(ms, t);
    string xmlString = Encoding.UTF8.GetString(ms.ToArray()); return xmlString;
    } } [Serializable()]
    [XmlRoot]
    public class Book
    {
    string _booknumber = "";
    [XmlElement]
    public string BookNumber
    {
    get { return _booknumber; }
    set { _booknumber = value; }
    } string _name = "";
    [XmlElement]
    public string Name
    {
    get { return _name; }
    set { _name = value; }
    }
    } [Serializable()]
    [XmlRoot]
    public class Person
    {
    string _personName = "";
    [XmlElement]
    public string PersonName
    {
    get { return _personName; }
    set { _personName = value; }
    }
    } }

    2.C#中泛型在方法Method上的实现

     

相关文章