Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

c# - How do I automatically display all properties of a class and their values in a string?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...