我有一个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();
}
}
}