2016-08-29 148 views
1

有對象的列表:C#獲取來自列表特定屬性的屬性對象

List<ConfigurationObjectBase> ObjectRegistry; 

具有以下屬性和上面的一些對象的與屬性飾:

[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)] 
public sealed class PropertyCanHaveReference : Attribute 
{ 
    public PropertyCanHaveReference(Type valueType) 
    { 
     this.ValueType = valueType; 
    } 

    public Type ValueType { get; set; } 
} 

現在,我想找到其屬性用該屬性裝飾的所有對象。

嘗試下面的代碼,好像我做錯了:

List<ConfigurationObjectBase> tmplist = ObjectRegistry.Where(o => (o.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(PropertyCanHaveReference), true).Length > 0))); 

感謝您的時間。

+3

不應該第二個'Where'是'Any'? –

+0

乍一看你的代碼看起來是正確的(儘管你可能想要堅持約定並調用屬性類「PropertyCanHaveReferenceAttribute」)。實際上會發生什麼「錯誤」?你會得到哪些錯誤信息或沒有結果?請提供無法運行的示例對象或[最小,完整且可驗證的示例](http://stackoverflow.com/help/mcve) –

回答

1

看來你有你展示的代碼行的一些語法錯誤。你可以將某些Where/Count組合轉換爲Any()。這個工作對我來說:

List<ConfigurationObjectBase> tmplist = 
     ObjectRegistry.Where(o => o.GetType().GetProperties().Any(p => 
       p.GetCustomAttributes(typeof(PropertyCanHaveReference), true).Any())).ToList(); 

所以你篩選出具有任何你的類型的屬性的任何屬性的所有對象。

您也可以使用通用GetCustomAttribute<T>()方法:

List<ConfigurationObjectBase> tmplist = 
     ObjectRegistry.Where(o => o.GetType().GetProperties().Any(p => 
        p.GetCustomAttribute<PropertyCanHaveReference>(true) != null)).ToList(); 

請考慮按照慣例PropertyCanHaveReferenceAttribute來命名屬性類。

0

這裏是一個代碼來獲得對象的名單,其中有它的屬性飾有自定義屬性:

 List<ConfigurationObjectBase> tmplist = ObjectRegistry.Where(o => 
      (o.GetType().GetProperties(System.Reflection.BindingFlags.Public | 
            System.Reflection.BindingFlags.NonPublic | 
      System.Reflection.BindingFlags.Instance).Where(
      prop => Attribute.IsDefined(prop, typeof(PropertyCanHaveReference)))).Any()).ToList(); 

您的代碼將只能得到公共屬性,已被裝飾。上面的代碼將得到:公共和非公開。

0

這System.Type的擴展方法應該工作:

public static IEnumerable<PropertyInfo> GetPropertiesWithAttribute<TAttribute>(this Type type) where TAttribute : Attribute 
{ 
    var properties = type.GetProperties(); 
    // Find all attributes of type TAttribute for all of the properties belonging to the type. 
    foreach (PropertyInfo property in properties) 
    { 
     var attributes = property.GetCustomAttributes(true).Where(a => a.GetType() == typeof(TAttribute)).ToList(); 
     if (attributes != null && attributes.Any()) 
     { 
      yield return property; 
     } 
    } 
}