忽略PropertyInfo中的集合属性

Luc*_*ini 9 c# properties propertyinfo

我有一个这个代码的函数:

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

我会避免检查"收集"属性; 现在我已经插入此控件:

 if (propertyInfo.PropertyType.Name.Contains("List")
     || propertyInfo.PropertyType.Name.Contains("Enumerable")
     || propertyInfo.PropertyType.Name.Contains("Collection"))
     continue;
Run Code Online (Sandbox Code Playgroud)

但是,它不喜欢我!

这是一个更好的方法吗?

Ant*_*ram 16

我在想你可能想检查属性实现类型的接口.(删除了冗余接口,因为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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我添加了代码以拒绝字符串,因为它实现了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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • IEnumerable <>实现IEnumerable,不需要检查IEnumerable <> (7认同)

Luk*_*keH 9

我可能会检查IEnumerable.

if ((typeof(string) != propertyInfo.PropertyType) 
    && typeof(IEnumerable).IsAssignableFrom(propertyInfo.PropertyType))
{
    continue;
}
Run Code Online (Sandbox Code Playgroud)


MaL*_*Lio 5

bool isCollection = typeof(System.Collections.IEnumerable)
                          .IsAssignableFrom(propertyInfo.PropertyType);
Run Code Online (Sandbox Code Playgroud)