2010-08-25 102 views
31

下面是我用於獲取IsDirty檢查類中所有公共屬性的初始狀態的一些代碼。如何知道PropertyInfo是否是一個集合

查看屬性是IEnumerable的最簡單方法是什麼?

乾杯,
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

我傷口什麼事做是增加了一些庫擴展如下

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

回答

37
if (typeof(IEnumerable).IsAssignableFrom(pi.PropertyType)) 
+25

注意,String是一個IEnumerable太 – 2013-11-11 19:06:50

+2

它解決了 http://stackoverflow.com/a/40376537/5996253 – 2016-11-02 09:35:12

1

嘗試

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

我最近注意到,'x.IsSubClassOf(Y)'返回false如果x ==問題年。在這種情況下,如果該屬性實際上是「IEnumerable」類型的,那麼該函數將返回false。 – 2010-08-25 21:02:30

+1

這很有趣,我真的從來沒有在這個確切的背景下實際使用這個邏輯,所以我很高興你指出了這一點。謝謝。 – 2010-08-26 00:33:51

12

我陀Soikin但可枚舉並不意味着贊同其實只是一個集合,因爲字符串也可枚舉,並返回字符一個接一個......

所以我建議使用

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

你對這個字符串當然是對的,但是你的解決方案失敗了(嘗試使用List ())。查看我的更新,瞭解我使用的代碼。乾杯! – Berryl 2013-03-16 12:18:36

+1

這個失敗是因爲沒有構造類型(如'List ')可以被分配給一個泛型類型('ICollection <>')(實際上,你不能聲明一個類型爲'ICollection <>'的變量)。所以最好使用'typeof(ICollection)'(如編輯器所建議的),這也將使它適用於非泛型集合。 – 2017-09-19 12:45:53

+0

非常確實 – Joanvo 2018-01-15 11:18:03

相關問題