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

标签 c# .net generics

我需要一种方法来循环遍历每个对象的属性并记录属性名称和值。然而,有时,我点击了一个列表对象的属性,整个事情就崩溃了。我从各种 SO 帖子中收集了以下条件,但每次都返回 false。想知道如何测试您的方法属性是否是通用集合类型?

类定义

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

方法

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

最佳答案

这是我用来识别日志中列表的代码:

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

编辑:我添加了一些额外的检查来过滤原始类型(int、bool 等)、枚举和字符串。

关于c# - 确定匿名类型的属性是否为泛型集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31819164/

相关文章:

java - 在 Matlab 中使用 Java 泛型类

c# - MVC 使操作链接执行提交

c# - 检查字符串的单词是否存在于字符串列表中

c# - 不要使用 FileOpenDialog 显示网络驱动器

c# - .NET 框架从何而来? Visual Studio 还是 Windows?

C# 使用泛型类而不指定类型

c# - 如何防止用户关闭我的 C# 应用程序?

c# - Linq to NHibernate 存储库实现细节

.net - String.Format不格式化字符串

c# - 从方法泛型推断类型