2017-08-01 170 views
0

我需要獲取一個PropertyDescriptorCollection,其中包含用自定義屬性裝飾的所有屬性。問題是,TypeDescriptor.GetProperties只能過濾所有屬性的精確匹配,所以如果我想要獲取所有屬性,不管屬性的屬性如何設置,我將不得不覆蓋過濾器數組中的所有可能性。獲取PropertyDescriptorCollection自定義屬性過濾屬性

這裏是我的attribue代碼:

[AttributeUsage(AttributeTargets.Property)] 
class FirstAttribute : Attribute 
{ 
    public bool SomeFlag { get; set; } 
} 

而且具有裝飾性的一類:

class Foo 
{ 
    [First] 
    public string SomeString { get; set; } 

    [First(SomeFlag = true)] 
    public int SomeInt { get; set; } 
} 

而且主:

static void Main(string[] args) 
{ 
    var firstPropCollection = TypeDescriptor.GetProperties(typeof(Foo), new Attribute[] {new FirstAttribute()}); 
    Console.WriteLine("First attempt: Filtering by passing an array with a new FirstAttribute"); 
    foreach (PropertyDescriptor propertyDescriptor in firstPropCollection) 
    { 
     Console.WriteLine(propertyDescriptor.Name); 
    } 

    Console.WriteLine(); 
    Console.WriteLine("Second attempt: Filtering by passing an an array with a new FirstAttribute with object initialization"); 
    var secondPropCollection = TypeDescriptor.GetProperties(typeof(Foo), new Attribute[] { new FirstAttribute {SomeFlag = true} }); 
    foreach (PropertyDescriptor propertyDescriptor in secondPropCollection) 
    { 
     Console.WriteLine(propertyDescriptor.Name); 
    } 

    Console.WriteLine(); 
    Console.WriteLine("Third attempt: I am quite ugly =(... but I work!"); 
    var thirdCollection = TypeDescriptor.GetProperties(typeof(Foo)).Cast<PropertyDescriptor>() 
     .Where(p => p.Attributes.Cast<Attribute>().Any(a => a.GetType() == typeof(FirstAttribute))); 
    foreach (PropertyDescriptor propertyDescriptor in thirdCollection) 
    { 
     Console.WriteLine(propertyDescriptor.Name); 
    } 

    Console.ReadLine(); 
} 

到目前爲止,只有這樣我讓它成功運作是第三次嘗試,我想知道是否有更直觀更優雅的方式。

輸出結果如下: enter image description here 正如你所看到的,我只能設法在最後一次嘗試時獲得兩個屬性。

在此先感謝

回答

1

我真的不知道我理解這個問題......你想有一個特定的屬性,無論該屬性值的所有屬性?

class Program 
{ 
    static void Main(string[] args) 
    { 
     var props = typeof(Foo).GetProperties(); 
     var filtered = props 
      .Where(x => x.GetCustomAttributes(typeof(FirstAttribute), false).Length > 0) 
      .ToList(); 
     var propertyDescriptor = TypeDescriptor.GetProperties(typeof(Foo)) 
      .Find(filtered[0].Name, false); 
    } 
} 
class Foo 
{ 
    [First] 
    public string SomeString { get; set; } 

    [First(SomeFlag = true)] 
    public int SomeInt { get; set; } 
} 
[AttributeUsage(AttributeTargets.Property)] 
class FirstAttribute : Attribute 
{ 
    public bool SomeFlag { get; set; } 
} 
+0

你的解決方案的問題是你正在使用'PropertyInfo []'檢索信息。我需要使用PropertyDescriptorCollection,因爲我確實需要PropertyDescriptor來匹配每個與條件匹配的屬性。 – taquion

+0

Type.GetProperties檢索一個PropertyInfo數組 – taquion

+0

你是對的。編輯我的帖子。您可以從您在代碼中迭代的集合中獲取匹配描述符。但取決於你多久稱此功能,你應該基準哪個功能更好地工作...... – Michael