C # meta programming-Let your code generate code-use reflection to override the automatic tostring ()

Source: Internet
Author: User

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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.