开发者

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

开发者 https://www.devze.com 2023-01-21 05:54 出处:网络
This question already has answers here: C#: Printing all properties of an object [duplicate] (9 answers)
This question already has answers here: C#: Printing all properties of an object [duplicate] (9 answers) Closed 6 years ago.

Imagine a class with many public properties. For some reason, it is impossible to refactor this class开发者_如何学C 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?


I think you can use a little reflection here. Take a look at Type.GetProperties().

public override string ToString()
{
    return GetType().GetProperties()
        .Select(info => (info.Name, Value: info.GetValue(this, null) ?? "(null)"))
        .Aggregate(
            new StringBuilder(),
            (sb, pair) => sb.AppendLine($"{pair.Name}: {pair.Value}"),
            sb => sb.ToString());
}


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


You can do this via reflection.

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


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


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消