5

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

3 回答 3

6
Console.WriteLine(property.GetValue(customer).ToString());

但是,这将非常缓慢。您可以通过GetGetMethod为每个属性创建一个委托来改进它。或者将带有属性访问表达式的表达式树编译到委托中。

于 2012-07-24T18:43:42.943 回答
5

您可以尝试以下方法:

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
于 2012-07-24T18:52:57.307 回答
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]));
        }
    }
}

请注意性能损失。

于 2012-07-24T19:03:05.720 回答