如何在字符串中自动显示类的所有属性及其值? [英] How do I automatically display all properties of a class and their values in a string?

查看:28
本文介绍了如何在字符串中自动显示类的所有属性及其值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想添加一个 ToString 覆盖来返回以下内容:

<前>属性 1:属性 1 的值 属性 2:属性 2 的值 ...

有没有办法做到这一点?

解决方案

我觉得你可以在这里稍微反思一下.看看Type.GetProperties().

公共覆盖字符串 ToS​​tring(){返回 GetType().GetProperties().Select(info => (info.Name, Value: info.GetValue(this, null) ?? "(null)")).总计的(新的 StringBuilder(),(某人,对) =>sb.AppendLine($"{pair.Name}: {pair.Value}"),某人 =>sb.ToString());}

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

Property 2: Value of property 2

...

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

这篇关于如何在字符串中自动显示类的所有属性及其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆