我有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 :(得分:6)
Console.WriteLine(property.GetValue(customer).ToString());
然而,这将非常缓慢。您可以使用GetGetMethod
改进它并为每个属性创建一个委托。或者将带有属性访问表达式的表达式树编译到委托中。
答案 1 :(得分: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 :(得分: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]));
}
}
}
请注意性能损失。