簡體   English   中英

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

[英]Check if property has an specified attribute, and then print value of it

我有一個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改進它並為每個屬性創建一個委托。 或者將具有屬性訪問表達式的表達式樹編譯到委托中。

您可以嘗試以下方法:

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
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]));
        }
    }
}

請注意性能損失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM