Attribute特性

[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; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值