我目前卡在输出对象值上。其中一些对象具有List<string>
属性,使用ToString()
方法会引起问题。以下是我在基类中使用的代码,用于将属性的名称和值组合成一个字符串。
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;
}
无论如何,检查属性是否为列表不起作用。这可能是一个愚蠢的问题或者使用反射的一种不好的方式,但我对此还很陌生,并且将感激任何帮助来弄清楚发生了什么。
prop.PropertyType
是否可以被视为IList<string>
类型。 - Nkosi