代码之家  ›  专栏  ›  技术社区  ›  mafu

如何在字符串中自动显示类的所有属性及其值?[副本]

  •  32
  • mafu  · 技术社区  · 14 年前

    这个问题已经有了答案:

    想象一个具有许多公共属性的类。出于某种原因,不可能将这个类重构成更小的子类。

    我想添加一个ToString重写,它返回以下行中的某些内容:

    Property 1: Value of property 1\n
    Property 2: Value of property 2\n
    ...
    

    有办法吗?

    5 回复  |  直到 11 年前
        1
  •  71
  •   Oliver    11 年前

    Type.GetProperties()

    private PropertyInfo[] _PropertyInfos = null;
    
    public override string ToString()
    {
        if(_PropertyInfos == null)
            _PropertyInfos = this.GetType().GetProperties();
    
        var sb = new StringBuilder();
    
        foreach (var info in _PropertyInfos)
        {
            var value = info.GetValue(this, null) ?? "(null)";
            sb.AppendLine(info.Name + ": " + value.ToString());
        }
    
        return sb.ToString();
    }
    
        2
  •  23
  •   PandaWood    12 年前

    public static string PropertyList(this object obj)
    {
      var props = obj.GetType().GetProperties();
      var sb = new StringBuilder();
      foreach (var p in props)
      {
        sb.AppendLine(p.Name + ": " + p.GetValue(obj, null));
      }
      return sb.ToString();
    }
    
        3
  •  3
  •   Yakimych    14 年前

    PropertyInfo[] properties = MyClass.GetType().GetProperties();
    foreach(PropertyInfo prop in properties)
    {
    ...
    }
    
        4
  •  1
  •   Andrew Bezzub    14 年前

    ToString() Reflections

    typeof(YourClass).GetProperties()
    
        5
  •  1
  •   Carlo V. Dango    11 年前