·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> 标签 Attribute

标签 Attribute

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

标签 Attribute

在一个类上面放一个标签,可以用来表示一些特定规则,比如某个对象的某个属性不想被json化,那么我们在它头上放个标签就行了,或是做ORM时指定某个Class对应的table名字等。

最后标签是通过反射来调用的,一个类只要继承了微软的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 string someData { get; set; } //公开属性还可以直接在标签上面写入    public Table(string str)    {        this.str = str;    }    public string str { get; set; }}//2个属性[Column("class")][Table("table class", someData = "ggc" )] //someData="ggc"是直接对attribute对象写入值! 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;}