我如何自动显示类的字符串中的所有属性和它们的值? [英] How do I automatically display all properties of a class and their values in a string?
本文介绍了我如何自动显示类的字符串中的所有属性和它们的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想象一下,一个班有许多公共属性。出于某种原因,这是不可能重构这个类分成更小的子类。
Imagine a class with many public properties. For some reason, it is impossible to refactor this class into smaller subclasses.
我想添加一个toString覆盖,返回沿着线的东西:
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?
推荐答案
我想你可以在这里用一点反思。看看<一href="http://msdn.microsoft.com/en-us/library/aky14axb.aspx"><$c$c>Type.GetProperties()$c$c>.
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();
}
这篇关于我如何自动显示类的字符串中的所有属性和它们的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文