迭代遍历集合并获取item.ToString()的GetValue反射

时间:2018-01-23 12:25:00

标签: c# .net reflection

Inside Class TestClass:

public HashSet<string> Test = new HashSet<string>();
public List<string> Test2 = new List<string>() {"item1"};
public String Test3 = "lol";

使用反射获取所有属性:

TestClass c = new TestClass();
var properties = c.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

现在我想只遍历集合属性:

var value = property.GetValue(c);
if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType) && property.PropertyType != typeof(string))
{
    var valueString = string.Empty;
    foreach (var item in (IEnumerable)value)
    {
        valueString += item.ToString() + " | ";
    }
}

工作正常。除非集合为空,我在item.ToString()上获取集合fullname而不是nothing / string.empty:

Output:
for the list I get a valueString with "item1" but for the HashSet I get a valueString of "TestClass.HashSet"

有什么方法可以解决这个问题吗?

0 个答案:

没有答案