【问题标题】:Ignore collection properties in PropertyInfo忽略 PropertyInfo 中的集合属性
【发布时间】:2010-05-14 14:02:21
【问题描述】:

我有这个代码的功能:

foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()){
//SOME CODE
if (propertyInfo.CanWrite)
    propertyInfo.SetValue(myCopy, propertyInfo.GetValue(obj, null), null);
}

我会避免检查“收藏”属性;现在我要插入这个控件:

 if (propertyInfo.PropertyType.Name.Contains("List")
     || propertyInfo.PropertyType.Name.Contains("Enumerable")
     || propertyInfo.PropertyType.Name.Contains("Collection"))
     continue;

但是,它不喜欢我!

哪种方法更好?

【问题讨论】:

    标签: c# properties propertyinfo


    【解决方案1】:

    我在想您可能想要检查属性类型实现的接口。 (删除了冗余接口,因为 IList 继承 ICollection 而 ICollection 继承 IEnumerable。)

    static void DoSomething<T>()
    {
        List<Type> collections = new List<Type>() { typeof(IEnumerable<>), typeof(IEnumerable) };
    
        foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
        {
            if (propertyInfo.PropertyType != typeof(string) && propertyInfo.PropertyType.GetInterfaces().Any(i => collections.Any(c => i == c)))
            {
                continue;
            }
    
            Console.WriteLine(propertyInfo.Name);
        }
    }
    

    我添加了不拒绝字符串的代码,因为它也实现了 IEnumerable,我想您可能希望保留这些代码。

    鉴于之前的集合接口列表的冗余,这样写代码可能更简单

    static void DoSomething<T>()
    {
        foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
        {
            if (propertyInfo.PropertyType != typeof(string)
                && propertyInfo.PropertyType.GetInterface(typeof(IEnumerable).Name) != null
                && propertyInfo.PropertyType.GetInterface(typeof(IEnumerable<>).Name) != null)
            {
                continue;
            }
    
            Console.WriteLine(propertyInfo.Name);
        }
    }
    

    【讨论】:

    • IEnumerable 实现了 IEnumerable,不需要检查 IEnumerable
    【解决方案2】:

    我可能会检查 IEnumerable

    if ((typeof(string) != propertyInfo.PropertyType) 
        && typeof(IEnumerable).IsAssignableFrom(propertyInfo.PropertyType))
    {
        continue;
    }
    

    【讨论】:

    • 哦哦,现在我有一个问题......这个条件也适用于字符串属性。有可能吗?
    • @LukePet:字符串实现了IEnumerable,因为它们是字符的集合。安东尼的回答特别排除了字符串,所以你选择那个是正确的(我已经更新了我的答案以效仿)。
    • 是否还有其他实现 IEnumerable 的基本类型,例如 'string'?
    • @LukePet:我不知道。
    【解决方案3】:
    bool isCollection = typeof(System.Collections.IEnumerable)
                              .IsAssignableFrom(propertyInfo.PropertyType);
    

    【讨论】:

      猜你喜欢
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 2019-08-24
      • 1970-01-01
      • 2019-12-19
      相关资源
      最近更新 更多