我有一个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();
}
}
}
要打印*属性*或*属性*的值吗? – 2012-07-24 18:47:27
具有ShowAttribute – 2012-07-24 18:49:51