简体   繁体   English

确定匿名类型的属性是否为泛型集合

[英]Determine if anonymous type's property is a generic collection

I need a method to cycle through each object's properties and log the property name and value. 我需要一个方法来遍历每个对象的属性并记录属性名称和值。 On occasion, however, I hit a property that is a list object and the whole thing crashes. 然而,偶尔,我点击了一个列表对象的属性,整个事情崩溃了。 I've gather the condition below from various SO posts but it returns false every time. 我从各种SO帖子中收集了以下条件,但每次都返回false。 Wondering how to test if your method property is a generic collection type? 想知道如何测试你的方法属性是否是泛型集合类型?

Class Definition 类定义

public class DtccProducer
{
    public string ProducerDateOfBirth { get; set; }
    public string ProducerGender { get; set; }
    public string TransactionType { get; set; }
    public List<BigAddress> Addresses { get; set; }
    public List<BigCommunicationItem> Communications { get; set; }
}

Method 方法

    private static void ParseProducer(object obj)
    {
        StringBuilder s = new StringBuilder();
        Type objType = obj.GetType();

        foreach (PropertyInfo info in objType.GetProperties())
        {
            string key = info.Name;

            Type propType = info.PropertyType;

            if (propType.IsGenericType && typeof(ICollection<>).IsAssignableFrom(propType.GetGenericTypeDefinition()))
            {
                // This condition never passes - always evaluates to false
            }
            else
            {
                string value = (string) info.GetValue(obj, null);
                _sb.AppendLine(key + ": " + value);                    
            }
        }
    }

This is the code I use to identify lists in my log: 这是我用来识别日志中列表的代码:

if (!propType.IsPrimitive && !propType.IsEnum && propType != typeof(string) && propType.GetInterfaces().Any(x => x.IsGenericType 
           && x.GetGenericTypeDefinition() == typeof(IEnumerable<>)))

Edit: I've added some additional checks to filter out primitive types (int's, bool's, etc.), enum's and strings. 编辑:我添加了一些额外的检查来过滤掉原始类型(int,bool等),枚举和字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM