C# Meta Programming - Let Your Code Generate Code - 利用反射重寫自動的ToString()

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   ar   for   sp   div   

我們在寫一些Model的時候,經常會重寫ToString,為了在控制台中進行列印或者更好的單元測試。

但是,如果Model的欄位非常多的時候,如此簡單的重複勞動經常會變成一件令人頭痛的事情,因為大家

都不想重複勞動,或者這種事情應該交給初級程式員或者畢業生去做。

看如下:

public class Customer{    public string FirstName { get; set; }    public string LastName { get; set; }    public int Age { get; set; }    public override string ToString()    {        string format = "First Name: {0}\nLast Name: {1}\nAge: {2}\n";        return string.Format(format, FirstName, LastName, Age);            }}

 

如果充分利用反射的特性,我們可以做一個擴充方法,請看如下:

public static class ObjectExtensions{    public static string ToStringReflection<T>(this T @this)    {        var query = from prop in @this.GetType().GetProperties(                    BindingFlags.Instance | BindingFlags.Public)                    where prop.CanRead                    select string.Format("{0}: {1}\n",                    prop.Name,                    prop.GetValue(@this, null));        string[] fields = query.ToArray();        StringBuilder format = new StringBuilder();        foreach (string field in fields)        {            format.Append(field);        }        return format.ToString();    }}


這樣,我們在原來的代碼中只要寫一句話:

namespace Zeus.Thunder.Test.Model{    public class Customer    {        public string FirstName { get; set; }        public string LastName { get; set; }        public int Age { get; set; }        public override string ToString()        {            return this.ToStringReflection();        }    }}


測試程式:

Customer customer = new Customer(){    FirstName = "Master",    LastName = "HaKu",    Age = 20};Console.WriteLine(customer.ToString());

 

運行結果如下:

FirstName: Master
LastName: HaKu
Age: 20

 

C# Meta Programming - Let Your Code Generate Code - 利用反射重寫自動的ToString()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.