Retrieve custom attribute parameter values?

若如初见. 提交于 2019-11-30 13:52:38

In this case, you'd first retrieve the relevant PropertyInfo, then call MemberInfo.GetCustomAttributes (passing in your attribute type). Cast the result to an array of your attribute type, then get at the HeaderText property as normal. 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. (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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!