2011-12-22 71 views
1

我有3個類(所有派生從相同的基類),我必須動態填充列表框與屬性名稱。通過屬性動態添加項目到列表框

我已經試過這樣

class Test : TestBase { 
    [NameAttribute("Name of the Person")] 
    public string PersonName { get; set; } 

    private DateTime Birthday { get; set; } 
    [NameAttribute("Birthday of the Person")] 
    public string PersonBDay { 
     get { 
      return this.bDay.ToShortDateString(); 
     } 
    } 
} 

... 
[AttributeUsage(AttributeTargets.Property)] 
public class NameAttribute : Attribute { 
    public string Name { get; private set; } 

    public NameAttribute(string name) { 
     this.Name = name; 
    } 
} 

是否有可能在我的對象,尋找具有屬性NameAttribute並獲得字符串形式的NameAttributeName屬性的所有屬性?

回答

2

您可以從Type.GetProperties檢查每個屬性,然後使用方法過濾具有必需屬性的屬性。

隨着LINQ的一點點,這看起來像:

var propNameTuples = from property in typeof(Test).GetProperties() 
        let nameAttribute = (NameAttribute)property.GetCustomAttributes 
           (typeof(NameAttribute), false).SingleOrDefault() 
        where nameAttribute != null 
        select new { Property = property, nameAttribute.Name }; 

foreach (var propNameTuple in propNameTuples) 
{ 
    Console.WriteLine("Property: {0} Name: {1}", 
         propNameTuple.Property.Name, propNameTuple.Name); 
} 

順便說一句,我還建議在聲明屬性是單隻能使用在AttributeUsage裝飾AllowMultiple = false

+0

你救了我的命:)謝謝! – kyjan 2011-12-22 08:58:34