Get parameter values ​​for custom attributes?

if I created an attribute:

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

which I applied to several of my properties in the class

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

In my view, I have a list of people that I show in the table. How can I get a HeaderText value to use as column headers? Something like...

 <th><%:HeaderText%></th> 
+6
c # custom-attributes
source share
2 answers

In this case, you must first get the corresponding PropertyInfo , and then call MemberInfo.GetCustomAttributes (passing in your attribute type). Pass the result to an array of your attribute type, and then get the HeaderText property as usual. Code example:

 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); } } } } 
+23
source share

Jon Skeet's solution is good if you allow multiple attributes of the same type to be declared in a property. (AllowMultiple = true)

Example:

 [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 suggest that you only need one attribute, allowed for each property. In this case, you can access the properties of the custom attribute with:

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

All Articles