反射 - 输出任何物体的最佳方式?

时间:2011-08-19 20:00:33

标签: c# .net reflection properties typedescriptor

  

可能重复:
  TypeDescriptor.GetProperties() vs Type.GetProperties()

如果我想要一个采用随机对象并输出(或以其他方式检索)每个包含的属性的方法,这将是最优雅和最强大的道路?

此问题来自我先前的问题here以及提出替代方法的评论。

  • 我之前使用TypeDescriptorPropertyDescriptor类的方式:

    public static void extract(object obj)
    {
        List<string> properties = new List<string>();
        foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
        {
            string name = descriptor.Name;
            object value = descriptor.GetValue(obj);
            properties.Add(name + " = " value);
        }
        if (properties.Count == 0)
            output(obj.ToString());
        else
            output(obj, string.Concat(properties));
    }
    
  • 建议的替代方案,使用Type.GetProperties():

    public static void extract(object obj)
    {
        List<string> properties = new List<string>();
        foreach (PropertyInfo property in obj.GetType().GetProperties())
        {
            string name = property.Name;
            object value = property.GetValue(obj, null);
            properties.Add(name + " = " value);
        }
        if (properties.Count == 0)
            output(obj.ToString());
        else
            output(obj, string.Concat(properties));
    }
    

到目前为止,我还没有使用过Reflection,也没有真正看到这两者有何区别。从一个到另一个有什么优势吗? 还有另外(更好)的方法吗?

1 个答案:

答案 0 :(得分:2)

public static class ObjectExtensions
{
    public static string Extract<T>(this T theObject)
    {
        return string.Join(
            ",",
            new List<string>(
                from prop in theObject.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
                where prop.CanRead
                select string.Format("{0} = {1}",
                prop.Name,
                prop.GetValue(theObject, null))).ToArray());
    }
}