码迷,mamicode.com
首页 > 其他好文 > 详细

Attribute特性

时间:2014-11-05 16:44:01      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:ar   使用   sp   bs   ad   ef   new   as   tt   

[AttributeUsage(AttributeTargets.All)]//指定Attribute的使用范围,比如只能在class级别使用
public class Column : Attribute
{
    public Column(string str)
    {
        this.str = str;
    }
    public string str { get; set; }
}
//第2个
[AttributeUsage(AttributeTargets.All)]
public class Table : Attribute
{
    public Table(string str)
    {
        this.str = str;
    }
    public string str { get; set; }
}

//2个属性
[Column("class")]
[Table("table class")]
public class Abc
{
    public string x { get; set; }
    [Column("attr")]
    public Int32 y { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
    //通过反射可以调用到这个类型头上的attr
    Type type = typeof(Abc);
 bool isGot = Attribute.IsDefined(type, typeof(Column)); //查看有没有某个Attribute Attribute[] attrs = Attribute.GetCustomAttributes(type); //批量获取 string xy = attrs.First().GetType().Name; //可以查看它的名字来选择想要的,或是看有没有想要的. Column column = (Column)Attribute.GetCustomAttribute(type, typeof(Column)); //强转 Column[] columns = (Column[])Attribute.GetCustomAttributes(type, typeof(Column)); column = columns[0]; string x = column.str; //调用方法或是公开属性等等都可以 //实例化之后也是可以一样拿 Abc a = new Abc(); PropertyInfo info = a.GetType().GetProperty("y"); Column attribute2 = (Column)Attribute.GetCustomAttribute(info, typeof(Column)); string xyz = attribute2.str; }

Attribute特性

标签:ar   使用   sp   bs   ad   ef   new   as   tt   

原文地址:http://www.cnblogs.com/ingstyle/p/4076313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!