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

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值