How to know if a PropertyInfo is a collection

天涯浪子 提交于 2019-12-31 08:32:59

问题


Below is some code I use to get the initial state of all public properties in a class for IsDirty checking.

What's the easiest way to see if a property is IEnumerable?

Cheers,
Berryl

  protected virtual Dictionary<string, object> _GetPropertyValues()
    {
        return _getPublicPropertiesWithSetters()
            .ToDictionary(pi => pi.Name, pi => pi.GetValue(this, null));
    }

    private IEnumerable<PropertyInfo> _getPublicPropertiesWithSetters()
    {
        return GetType().GetProperties().Where(pi => pi.CanWrite);
    }

UPDATE

What I wound up doing was adding a few library extensions as follows

    public static bool IsNonStringEnumerable(this PropertyInfo pi) {
        return pi != null && pi.PropertyType.IsNonStringEnumerable();
    }

    public static bool IsNonStringEnumerable(this object instance) {
        return instance != null && instance.GetType().IsNonStringEnumerable();
    }

    public static bool IsNonStringEnumerable(this Type type) {
        if (type == null || type == typeof(string))
            return false;
        return typeof(IEnumerable).IsAssignableFrom(type);
    }

回答1:


if ( typeof( IEnumerable ).IsAssignableFrom( pi.PropertyType ) )



回答2:


I agree with Fyodor Soikin but the fact that is Enumerable does not mean that is only a Collection since string is also Enumerable and returns the characters one by one...

So i suggest using

if (typeof(ICollection<>).IsAssignableFrom(pi.PropertyType))



回答3:


Try

private bool IsEnumerable(PropertyInfo pi)
{
   return pi.PropertyType.IsSubclassOf(typeof(IEnumerable));
}


来源:https://stackoverflow.com/questions/3569811/how-to-know-if-a-propertyinfo-is-a-collection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!