想象一个有很多公共属性的类。由于某些原因,无法将该类重构为更小的子类。
我想添加一个ToString重写,返回类似以下内容:
属性1:属性1的值\n 属性2:属性2的值\n ...
有没有办法做到这一点?
想象一个有很多公共属性的类。由于某些原因,无法将该类重构为更小的子类。
我想添加一个ToString重写,返回类似以下内容:
属性1:属性1的值\n 属性2:属性2的值\n ...
有没有办法做到这一点?
我认为你可以在这里使用一些反射。看一下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的答案是扩展方法(我认为很适合它)
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();
}
PropertyInfo[] properties = MyClass.GetType().GetProperties();
foreach(PropertyInfo prop in properties)
{
...
}
ToString()
方法。如果不能,则可以使用 Reflections 从 Type 对象中读取信息:typeof(YourClass).GetProperties()
_PropertyInfos = this.GetType().GetProperties();
。 - Conrad Frix_PropertyInfos
?这似乎违反了所有编码规范。 - Kellen Stuart