使用C#中的Reflection检查属性是否为列表 [英] Check if Property is List using Reflection in C#

查看:109
本文介绍了使用C#中的Reflection检查属性是否为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻,我一直坚持提出对象的值.其中一些确实具有List<string>属性,这会导致使用ToString() Method引起麻烦.这是我在基类中使用的代码,用于将属性的名称和值转换为字符串.

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.

推荐答案

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

这篇关于使用C#中的Reflection检查属性是否为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆