检索自定义属性参数值?

Rus*_*sby 10 c# custom-attributes

如果我创建了一个属性:

public class TableAttribute : Attribute {
    public string HeaderText { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我在课堂上申请了一些我的房产

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

在我的视图中,我有一个显示在表格中的人员列表..如何检索HeaderText的值以用作我的列标题?就像是...

<th><%:HeaderText%></th>
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 31

在这种情况下,您首先检索相关的PropertyInfo,然后调用MemberInfo.GetCustomAttributes(传入您的属性类型).将结果转换为属性类型的数组,然后HeaderText照常访问属性.示例代码:

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


Scu*_*eve 5

如果您允许在一个属性上声明多个相同类型的属性,Jon Skeet 的解决方案是很好的。(AllowMultiple = true)

前任:

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

在您的情况下,我假设您只希望每个属性允许一个属性。在这种情况下,您可以通过以下方式访问自定义属性的属性:

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