检查属性是否具有指定的属性,然后打印它的值

Bar*_*ğlu 4 .net c#

我有一个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道如何检查属性是否有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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*igt 6

Console.WriteLine(property.GetValue(customer).ToString());
Run Code Online (Sandbox Code Playgroud)

但是,这将非常缓慢.您可以使用GetGetMethod每个属性创建委托并为其创建委托.或者将具有属性访问表达式的表达式树编译到委托中.


Mar*_*tus 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是

 Name
Run Code Online (Sandbox Code Playgroud)

如果你想要财产的价值:

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出在这里:

Name1
Name2
Name3
Run Code Online (Sandbox Code Playgroud)