C# 检索自定义属性参数值?

C# 检索自定义属性参数值?,c#,custom-attributes,C#,Custom Attributes,如果已创建属性: public class TableAttribute : Attribute { public string HeaderText { get; set; } } 我将其应用于类中的一些属性 public class Person { [Table(HeaderText="F. Name")] public string FirstName { get; set; } } 在我看来,我在一张表格中显示了一份人员列表。。如何检索HeaderText的

如果已创建属性:

public class TableAttribute : Attribute {
    public string HeaderText { get; set; }
}
我将其应用于类中的一些属性

public class Person {
    [Table(HeaderText="F. Name")]
    public string FirstName { get; set; }
}
在我看来,我在一张表格中显示了一份人员列表。。如何检索HeaderText的值以用作列标题?类似于

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

在本例中,首先检索相关的
属性info
,然后调用(传递属性类型)。将结果强制转换为属性类型的数组,然后按常规获取
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);
            }
        }
    }
}

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

例:

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

var tableAttribute= propertyInfo.GetCustomAttribute<TableAttribute>();
Console.Write(tableAttribute.HeaderText);
// Outputs "F. Name" when accessing FirstName
// Outputs "L. Name" when accessing LastName
var tableAttribute=propertyInfo.GetCustomAttribute();
编写(tableAttribute.HeaderText);
//访问FirstName时输出“F.Name”
//访问LastName时输出“L.Name”
var tableAttribute= propertyInfo.GetCustomAttribute<TableAttribute>();
Console.Write(tableAttribute.HeaderText);
// Outputs "F. Name" when accessing FirstName
// Outputs "L. Name" when accessing LastName