Check if Property is List using Reflection in C#

2019-09-10 16:44发布

I'm stuck at putting out the values of my objects at the moment. Some of them do have List<string>properties which causes trouble by using the ToString()Method. Here is the code I use in my base class to get the name and the value of the properties into a string.

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;
    }

Anyhow, the check if the propertie is a List does not work. This might be a dumb question and or a bad way to work with reflection but I'm kinda new to it and will appreciate any help to figure out what is going on.

2条回答
够拽才男人
2楼-- · 2019-09-10 17:23
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;
}
查看更多
闹够了就滚
3楼-- · 2019-09-10 17:44

I'd do this;

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.    
    }   
}

Also, instead of concatenatings strings with the + operator, take a look at StringBuilder, which is better for memory and speed.

查看更多
登录 后发表回答