標籤: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()