当前位置: 首页 > 编程语言 > C#

检索自定义属性参数值?分享

时间:2023-04-10 17:47:23 C#

检索自定义属性参数值?如果我创建一个属性:publicclassTableAttribute:Attribute{publicstringHeaderText{get;放;}}我申请了类中的一些属性publicclassPerson{[Table(HeaderText="F.Name")]publicstringFirstName{get;放;在我看来,我在表格中显示了一个人员列表。如何检索HeaderText的值以用作我的列标题?就像...在这种情况下,您首先检索相关的PropertyInfo,然后调用MemberInfo.GetCustomAttributes(传入您的属性类型)。将结果转换为属性类型数组,然后照常获取HeaderText属性。示例代码:使用系统;使用System.Reflection;[AttributeUsage(AttributeTargets.Property)]publicclassTableAttribute:Attribute{publicstringHeaderText{get;放;}}publicclassPerson{[Table(HeaderText="F.Name")]publicstringFirstName{get;放;}[Table(HeaderText="L.Name")]publicstringLastName{get;放;}}publicclassTest{publicstaticvoidMain(){foreach(varpropintypeof(Person).GetProperties()){varattrs=(TableAttribute[])prop.GetCustomAttributes(typeof(TableAttribute),false);foreach(varattrinattrs){Console.WriteLine("{0}:{1}",prop.Name,attr.HeaderText);如果允许在属性上声明相同类型的多个属性,则JonSkeet的解决方案很好。(AllowMultiple=true)示例:[Table(HeaderText="F.Name1")][Table(HeaderText="F.Name2")][Table(HeaderText="F.Name3")]publicstringFirstName{得到;放;在你的情况下,我假设你只希望每个属性允许一个属性。这种情况下,可以通过以下方式访问自定义属性的属性:以上是C#学习教程:Retrievingcustompropertyparametervalues?分享的所有内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——vartableAttribute=propertyInfo.GetCustomAttribute();Console.Write(tableAttribute.HeaderText);//访问FirstName时输出"F.Name"//访问LastName时输出"L.Name"本文整理自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: