自动输出类的字段及值

有点时候在测试的时候希望打印输出返回对象的各字段的值,如果每个都人为的增加ToString方法的话会很繁琐,采用下面的代码可以很方便的列出对象的各字段值:

using System;
using System.Linq;
using System.Reflection;

namespace LucienBao.Common
{
    public static class ToStringHelper
    {
        public static string ToString(object obj)
        {
            Type t = obj.GetType();
            FieldInfo[] fis = t.GetFields();
            return string.Join(Environment.NewLine,
                                fis.Select<FieldInfo, string>
                                    (p => p.Name + ":" + p.GetValue(obj).ToString()).ToArray()
                                );
        }
    }
}
原文地址:https://www.cnblogs.com/lucienbao/p/Reflection_FieldInfo.html