使用C#中的反射检查属性是否为列表

时间:2016-07-27 15:56:01

标签: c# list reflection tostring

我现在坚持要把我的物品的价值放在一边。其中一些属性具有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;
    }

无论如何,检查属性是否为列表不起作用。这可能是一个愚蠢的问题,也可能是一个糟糕的反思方法,但我对它有点新意,并会感谢任何帮助来弄清楚发生了什么。

2 个答案:

答案 0 :(得分:1)

我这样做;

var property = prop.GetValue(this);

// try to cast as IEnumerable<string> -- will set to null if it's not.
var propertyStrings = property as IEnumerable<string>;
if (propertyStrings != null) {
    foreach(var s in propertyStrings) {
        // do something here with your strings.    
    }   
}

此外,不要使用+运算符连接字符串,而是查看StringBuilder,这对于内存和速度更好。

答案 1 :(得分:1)

public override string ToString()
{
    StringBuilder content = new StringBuilder();
    foreach (var prop in this.GetType().GetProperties())
    {
        var propertyType = prop.PropertyType;
        var propertyValue = prop.GetValue(this);
        if (propertyValue != null)
        {
            if (propertyValue is IEnumerable<string>)
                content.AppendFormat("{0} = {1}", prop.Name, PrintList(propertyValue as IEnumerable<string>));
            else
                content.AppendFormat("{0} = {1}", prop.Name, propertyValue.ToString());
        }
        else
            content.AppendFormat("{0} = null", prop.Name);
        content.AppendLine();
    }

    return content.ToString();
}

private string PrintList(IEnumerable<string> list)
{
    var content = string.Join(",", list.Select(i => string.Format("[{0}]", i)));
    return content;
}