2016-08-29 8 views
1

は、オブジェクトの一覧有する物体:私はしたい、今すぐC#のリストから特定の属性を持つプロパティを取得

[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> ObjectRegistry; 

をプロパティがその属性で装飾されているすべてのオブジェクトを検索します。お時間を

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

だから、あなたはあなたのタイプの任意の属性を持つ任意のプロパティを持つすべてのオブジェクトをフィルタリング。

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

が規則PropertyCanHaveReferenceAttributeに応じて、あなたの属性クラスに名前を付けることを検討してください:

また、ジェネリックGetCustomAttribute<T>()メソッドを使用することができます。あなたのコードが施されており、唯一のパブリックプロパティを、なるだろう

 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

は、カスタム属性が飾ら性質のしているオブジェクトのリストを取得するためのコードです。上記のコードは公開と非公開の両方を取得します。

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; 
     } 
    } 
} 
関連する問題