如何知道一个的PropertyInfo是一家集 [英] How to know if a PropertyInfo is a collection

查看:134
本文介绍了如何知道一个的PropertyInfo是一家集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一些代码,我用它来获得在IsDirty检查类的所有公共属性的初始状态。



什么是看是否有属性是最简单的方法IEnumerable的?



干杯,结果
Berryl

 受保护的虚拟字典<字符串对象> _GetPropertyValues​​()
{
返回_getPublicPropertiesWithSetters()
.ToDictionary(PI => pi.Name,PI => pi.GetValue(这一点,空));
}

私人的IEnumerable<&的PropertyInfo GT; 。_getPublicPropertiesWithSetters()
{
返回的GetType()的GetProperties(),其中(PI => pi.CanWrite)。
}



更新



我清盘做的是增加了一些库扩展如下:

 公共静态布尔IsNonStringEnumerable(此的PropertyInfo PI){
返回PI = NULL&放大器;!&安培; pi.PropertyType.IsNonStringEnumerable();
}

公共静态布尔IsNonStringEnumerable(此对象实例){
返回实例= NULL&放大器;!&安培; instance.GetType()IsNonStringEnumerable()。
}

公共静态布尔IsNonStringEnumerable(这种类型的类型){
如果(类型== NULL ||类型== typeof运算(字符串))
返回FALSE;
返回的typeof(IEnumerable的).IsAssignableFrom(类型);
}


解决方案

 如果(typeof运算(IEnumerable的).IsAssignableFrom(pi.PropertyType))


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

解决方案

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

这篇关于如何知道一个的PropertyInfo是一家集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆