我有一個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