2012-07-24 62 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])); 
     } 
    } 
} 

请注意性能受到影响。