2012-07-24 58 views
4

我有一個ShowAttribute,我正在使用這個屬性來標記一些類的屬性。我想要的是,通過具有Name屬性的屬性打印值。我怎樣才能做到這一點 ?檢查屬性是否有指定的屬性,然後打印它的值

public class Customer 
{ 
    [Show("Name")] 
    public string FirstName { get; set; } 

    public string LastName { get; set; } 

    public Customer(string firstName, string lastName) 
    { 
     this.FirstName = firstName; 
     this.LastName = lastName; 
    } 
} 

class ShowAttribute : Attribute 
{ 
    public string Name { get; set; } 

    public ShowAttribute(string name) 
    { 
     Name = name; 
    } 
} 

我知道如何檢查屬性是否有ShowAttribute,但我不知道如何使用它。

var customers = new List<Customer> { 
    new Customer("Name1", "Surname1"), 
    new Customer("Name2", "Surname2"), 
    new Customer("Name3", "Surname3") 
}; 

foreach (var customer in customers) 
{ 
    foreach (var property in typeof (Customer).GetProperties()) 
    { 
     var attributes = property.GetCustomAttributes(true); 

     if (attributes[0] is ShowAttribute) 
     { 
      Console.WriteLine(); 
     } 
    } 
} 
+0

要打印*屬性*或*屬性*的值嗎? – 2012-07-24 18:47:27

+0

具有ShowAttribute – 2012-07-24 18:49:51

回答

6
Console.WriteLine(property.GetValue(customer).ToString()); 

然而,這將是非常緩慢的。您可以通過GetGetMethod併爲每個屬性創建一個委託來改善此問題。或者將具有屬性訪問表達式的表達式樹編譯成委託。

+1

+1的額外建議的財產的價值 – 2012-07-24 19:11:13

4

你可以嘗試以下方法:

var type = typeof(Customer); 

foreach (var prop in type.GetProperties()) 
{ 
    var attribute = Attribute.GetCustomAttribute(prop, typeof(ShowAttribute)) as ShowAttribute; 

    if (attribute != null) 
    { 
     Console.WriteLine(attribute.Name); 
    } 
} 

輸出是

Name 

如果您希望屬性的值:

foreach (var customer in customers) 
{ 
    foreach (var property in typeof(Customer).GetProperties()) 
    { 
     var attributes = property.GetCustomAttributes(false); 
     var attr = Attribute.GetCustomAttribute(property, typeof(ShowAttribute)) as ShowAttribute; 

     if (attr != null) 
     { 
      Console.WriteLine(property.GetValue(customer, null)); 
     } 
    } 
} 

和輸出是在這裏:

Name1 
Name2 
Name3 
2
foreach (var customer in customers) 
{ 
    foreach (var property in typeof (Customer).GetProperties()) 
    { 
     if (property.IsDefined(typeof(ShowAttribute)) 
     { 
      Console.WriteLine(property.GetValue(customer, new object[0])); 
     } 
    } 
} 

請注意性能受到影響。