How do I automatically display all properties of a class and their values in a string? [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-11-26 08:23:50

问题


This question already has an answer here:

  • C#: Printing all properties of an object [duplicate] 9 answers

Imagine a class with many public properties. For some reason, it is impossible to refactor this class into smaller subclasses.

I\'d like to add a ToString override that returns something along the lines of:

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

Is there a way to do this?


回答1:


I think you can use a little reflection here. Take a look at 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:


@Oliver's answer as an extension method (which I think suits it well)

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:


You can do this via reflection.

PropertyInfo[] properties = MyClass.GetType().GetProperties();
foreach(PropertyInfo prop in properties)
{
...
}



回答4:


If you have access to the code of the class you need then you can just override ToString() method. If not then you can use Reflections to read information from the Type object:

typeof(YourClass).GetProperties()



回答5:


You can take inspiration from a more elaborate introspection of state from the StatePrinter package class introspector



来源:https://stackoverflow.com/questions/4023462/how-do-i-automatically-display-all-properties-of-a-class-and-their-values-in-a-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!