检索自定义属性参数值?
如果我创建了一个属性:
public class TableAttribute : Attribute { public string HeaderText { get; set; } }
我适用于课堂上的一些属性
public class Person { [Table(HeaderText="F. Name")] public string FirstName { get; set; } }
在我的视图中,我有一个显示在表格中的人员列表..如何检索HeaderText的值以用作我的列标题? 就像是…
在这种情况下,您首先检索相关的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); } } } }
如果允许在属性上声明相同类型的多个属性,Jon Skeet的解决方案很好。 (AllowMultiple = true)
例如:
[Table(HeaderText="F. Name 1")] [Table(HeaderText="F. Name 2")] [Table(HeaderText="F. Name 3")] public string FirstName { get; set; }
在您的情况下,我假设您只希望每个属性允许一个属性。 在这种情况下,您可以通过以下方式访问自定义属性的属性:
var tableAttribute= propertyInfo.GetCustomAttribute(); Console.Write(tableAttribute.HeaderText); // Outputs "F. Name" when accessing FirstName // Outputs "L. Name" when accessing LastName