我们在写一些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