if开发者_StackOverflow社区 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? Something like...
<th><%:HeaderText%></th>
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
精彩评论