反射-输出任何对象的最佳方式

本文关键字:最佳 方式 对象 任何 输出 反射 | 更新日期: 2023-09-27 18:06:14

可能重复:
TypeDescriptor。GetProperties((与Type。GetProperties((

如果我想要一个方法,它接受一个随机对象并输出(或以其他方式检索(每个包含的属性,那么哪条路最优雅、最稳健?

这个问题源于我之前在这里提出的问题,以及提出另一种方法的评论。

  • 按照我以前的方法,使用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));
    }
    
  • 建议的替代方案,使用类型。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合作过,也没有真正看到这两者有什么不同。两者之间有什么优点吗?还有其他(更好的(方法吗?

反射-输出任何对象的最佳方式

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