【发布时间】:2016-07-27 15:56:00
【问题描述】:
我现在被困在展示我的对象的价值。其中一些确实有List<string>properties,使用ToString()Method 会导致麻烦。这是我在基类中使用的代码,用于将属性的名称和值转换为字符串。
public override string ToString()
{
string content = "";
foreach (var prop in this.GetType().GetProperties())
{
if (prop.PropertyType is IList<string> && prop.GetType().IsGenericType && prop.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>)))
content += prop.Name + " = " + PrintList((List<string>)prop.GetValue(this));
else
content += prop.Name + " = " + prop.GetValue(this) + "\r\n";
}
content += "\r\n";
return content;
}
private string PrintList(List<string> list)
{
string content = "[";
int i = 0;
foreach (string element in list)
{
content += element;
if (i == list.Count)
content += "]";
else
content += ", ";
}
return content;
}
无论如何,检查属性是否为列表不起作用。这可能是一个愚蠢的问题,或者是一种不好的反思方式,但我对它有点陌生,如果能帮助我弄清楚发生了什么,我将不胜感激。
【问题讨论】:
-
try 是 IEnumerable
-
prop.PropertyType.IsAssignableFrom(typeof(IList<string>))
标签: c# list reflection tostring