我有一个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();
}
}
}
最佳答案
Console.WriteLine(property.GetValue(customer).ToString());
但是,这会很慢。您可以使用 GetGetMethod
改进它并为每个属性创建一个委托(delegate)。或者将带有属性访问表达式的表达式树编译成委托(delegate)。
关于c# - 检查属性是否具有指定的属性,然后打印它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11637255/