简体   繁体   English

检索自定义属性参数值?

[英]Retrieve custom attribute parameter values?

if i have created an attribute: 如果我创建了一个属性:

public class TableAttribute : Attribute {
    public string HeaderText { get; set; }
}

which i apply to a few of my properties in a class 我在课堂上申请了一些我的房产

public class Person {
    [Table(HeaderText="F. Name")]
    public string FirstName { get; set; }
}

in my view i have a list of people which i am displaying in a table.. how can i retrieve the value of HeaderText to use as my column headers? 在我的视图中,我有一个显示在表格中的人员列表..如何检索HeaderText的值以用作我的列标题? Something like... 就像是...

<th><%:HeaderText%></th>

In this case, you'd first retrieve the relevant PropertyInfo , then call MemberInfo.GetCustomAttributes (passing in your attribute type). 在这种情况下,您首先检索相关的PropertyInfo ,然后调用MemberInfo.GetCustomAttributes (传入您的属性类型)。 Cast the result to an array of your attribute type, then get at the HeaderText property as normal. 将结果转换为属性类型的数组,然后正常获取HeaderText属性。 Sample code: 示例代码:

using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Property)]
public class TableAttribute : Attribute
{
    public string HeaderText { get; set; }
}

public class Person
{
    [Table(HeaderText="F. Name")]
    public string FirstName { get; set; }

    [Table(HeaderText="L. Name")]
    public string LastName { get; set; }
}

public class Test 
{
    public static void Main()
    {
        foreach (var prop in typeof(Person).GetProperties())
        {
            var attrs = (TableAttribute[]) prop.GetCustomAttributes
                (typeof(TableAttribute), false);
            foreach (var attr in attrs)
            {
                Console.WriteLine("{0}: {1}", prop.Name, attr.HeaderText);
            }
        }
    }
}

Jon Skeet's solution is good if you allow multiple attributes of the same type to be declared on a property. 如果允许在属性上声明相同类型的多个属性,Jon Skeet的解决方案很好。 (AllowMultiple = true) (AllowMultiple = true)

ex: 例如:

[Table(HeaderText="F. Name 1")]
[Table(HeaderText="F. Name 2")]
[Table(HeaderText="F. Name 3")]
public string FirstName { get; set; }

In your case, I would assume you only want one attribute allowed per property. 在您的情况下,我假设您只希望每个属性允许一个属性。 In which case, you can access the properties of the custom attribute via: 在这种情况下,您可以通过以下方式访问自定义属性的属性:

var tableAttribute= propertyInfo.GetCustomAttribute<TableAttribute>();
Console.Write(tableAttribute.HeaderText);
// Outputs "F. Name" when accessing FirstName
// Outputs "L. Name" when accessing LastName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM