When writing some models, we often rewrite tostring to print or better unit tests on the console.
However, when there are many model fields, such simple repetitive work will often become a headache, because
They do not want to repeat work, or they should be handed over to junior programmers or graduates.
See the following:
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); }}
If we make full use of the reflection feature, we can make an extension method, as shown below:
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(); }}
In this way, we only need to write one sentence in the original code:
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(); } }}
Test procedure:
Customer customer = new Customer(){ FirstName = "Master", LastName = "HaKu", Age = 20};Console.WriteLine(customer.ToString());
The running result is as follows:
Firstname: Master
Lastname: Haku
Age: 20
C # meta programming-Let your code generate code-use reflection to override the automatic tostring ()