[Asp.net基础]Attribute特性备忘

Attribute 是什么

Attribute 是一种可由用户自由定义的修饰符(Modifier),可以用来修饰各种需要被修饰的目标。
简单的说,Attribute就是一种“附着物” —— 就像牡蛎吸附在船底或礁石上一样。
这些附着物的作用是为它们的附着体追加上一些额外的信息(这些信息就保存在附着物的体内)—— 比如“这个类是我写的”或者“这个函数以前出过问题”等等。

Attribute 的作用

特性Attribute 的作用是 添加元数据
元数据可以被工具支持,比如:编译器用元数据来辅助编译,调试器用元数据来调试程序。

个人理解

注释是写给人看的. 而Attribute是写给程序看的. 在某个对象上加上注释, 在运行的时候通过反射可以拿到这个注释.
从而进行一些操作.

示例

[Name("中文名","谢霆锋"),Name("英文名","Nic")]
        public class Student { }
public class School {
[Name("中文名", "谢霆锋"), Name("英文名", "Nic")]
            public string schoolname { get{return "牛逼大学";} }
        }
[AttributeUsage(AttributeTargets.All,AllowMultiple=true)]
    public class Name:System.Attribute
    {
        public string Key { get; set; }
        public string Value { get; set; }
        public Name(string key, string value) {
            Key = key;
            Value = value;
        }
    }

//获取类的特性
            var attrs= Attribute.GetCustomAttributes(typeof(Student));
            Response.Write("<br>");
            Response.Write("类的特性有");
            foreach (var item in attrs)
            {
                var t=(Name)item;
                Response.Write("<br>");
                Response.Write((t).Key+" : "+t.Value+" , "+t.TypeId.ToString());
            }

//获取属性的特性. 同样获取方法, 字段,等的特性都是这样
            var Properties = typeof(School).GetProperties();
            Response.Write("<br>"); Response.Write("<br>");
            Response.Write("属性的特性有");
            foreach (var item in Properties)
            {
                foreach (var attr in item.GetCustomAttributes(false))
                {
                    var t = (Name)attr;
                    Response.Write("<br>");
                    Response.Write((t).Key + " : " + t.Value + " , " + t.TypeId.ToString());
                }
            }

这样. 我们在运行的时候得到了Name类的实例. 输出了Name的属性

你可能感兴趣的:([Asp.net基础]Attribute特性备忘)