2016-10-05 34 views
1

您好我需要檢查使用反射屬性是IEnumerable類型但不IEnumerable的字符串和值類型,但只有IEnumerable的非字符串引用類型。檢查使用反射如果屬性是IEnumerable只有引用類型,但不是字符串或值類型

現在我的代碼部分:

private bool IsEnumerable(PropertyInfo propertyInfo) 
{ 
    return propertyInfo.PropertyType.GetInterfaces().Contains(typeof(IEnumerable)) && 
      propertyInfo.PropertyType != typeof(string); 
} 

如果屬性爲IEnumerable<MyCustomType>這是確定的,但如果它是IEnumerable<string>我的方法應該返回false。

+1

你想要[Type.GetGenericArguments](https://msdn.microsoft.com/en-us/library/system.type.getgenericarguments(v = vs.110).aspx) – Jonesopolis

+0

如果它同時包含'IEnumerable < MyCustomType>'和'IEnumerable '? – PetSerAl

回答

3

您可以檢查該類型的實施IEnumerable<T>接口的GenericTypeArguments,以確保它是兩者的不字符串類型,而不是一個值類型:

public static bool IsEnumerable(PropertyInfo propertyInfo) 
{ 
    var propType = propertyInfo.PropertyType; 

    var ienumerableInterfaces = propType.GetInterfaces() 
      .Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == 
         typeof(IEnumerable<>)).ToList(); 

    if (ienumerableInterfaces.Count == 0) return false; 

    return ienumerableInterfaces.All(x => 
       x.GenericTypeArguments[0] != typeof(string) && 
       !x.GenericTypeArguments[0].IsValueType);  
} 

此更新版本適當的處理,其中有多個案例IEnumerable<T>定義,其中沒有定義IEnumerable<T>,並且通用實現類的類型與實現的IEnumerable<T>的類型參數不匹配。

+0

還有一件事:'public IEnumerable P5 {get;組; }'。 – PetSerAl

+0

@PetSerAl我認爲這不是OP所要求的,因爲它沒有實現接口。 –

相關問題