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 に答える