检索自定义属性参数值? [英] Retrieve custom attribute parameter values?

查看:105
本文介绍了检索自定义属性参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我已经创建了一个属性:

 公共类TableAttribute:属性{
公共字符串的HeaderText {搞定;组; }
}



我申请我的一些特性的一类。



 公共类Person {
表(的HeaderText =楼名)]
公共字符串名字{得到;组; }
}

在我看来,我有我在我展示人的名单表..我怎么可以检索的HeaderText的值作为我的列标题使用?喜欢的东西...

 百分位><%:的HeaderText%GT;< /第i 


解决方案

在这种情况下,你会先检索相关的PropertyInfo ,然后调用 MemberInfo.GetCustomAttributes (传递你的属性类型)。铸造结果到你的属性类型的数组,然后我们就到的HeaderText 属性为正常。示例代码:

 使用系统; 
使用的System.Reflection;

[AttributeUsage(AttributeTargets.Property)
公共类TableAttribute:属性
{
公共字符串的HeaderText {搞定;组; }
}

公共类Person
{
表(=的HeaderTextF名称)]
公共字符串名字{获得;组; }

表(=的HeaderTextL名称)]
公共字符串名字{获得;组; }
}

公共类测试
{
公共静态无效的主要()
{
的foreach(VAR道具在typeof运算(人) .GetProperties())
{
VAR ATTRS =(TableAttribute [])prop.GetCustomAttributes
(typeof运算(TableAttribute),FALSE);
的foreach(在ATTRS VAR attr)使用
{
Console.WriteLine({0}:{1},prop.Name,attr.HeaderText);
}
}
}
}


if 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);
            }
        }
    }
}

这篇关于检索自定义属性参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆