Mvc总结-特性(Attributes)

1.定义

  MSDN定义:公共语言运行时允许你添加类似关键字的描述声明,叫做attributes, 它对程序中的元素进行标注,如类型、字段、方法和属性等。Attributes和Microsoft .NET Framework文件的元数据保存在一起,可以用来向运行时描述你的代码,或者在程序运行的时候影响应用程序的行为。具体使用示例如下:

[Obsolete]  //此属性为废弃
public string Demo()
{
    return "";
}

  该方法前面标明[Obsolete]特性,调用该方法时则提示”方法已过时“提示。

2.应用场景

  特性可与反射方法搭配,可返回引用该特性方法或者类的信息,用于描述展示引用对象信息。具体如下:

    //自定义作者特性
    public class Author : System.Attribute
    {
        public string Name { get; set; }    //名称
        public double Version { get; set; } //版本    

        public Author(string _name, double _version)
        {
            this.Name = _name;
            this.Version = _version;
        }

        public string GetInfo()
        {
            return "名称:" + Name + ",版本:" + Version;
        }
    }
    
    //引用特性类
    [Author("HJX", 1.1)]
    class FirstClass
    {
        // ...
    }

    //利用反射方法,调用特性输出类信息
    public string Index()
    {
            //调用打印作者方法
            string ExcultResult = PrintAuthorInfo(typeof(FirstClass));
            returnExcultResult;
    }

        //具体反射方法实现
        private static string PrintAuthorInfo(System.Type t)
        {
            string Result = "";
            System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  

            foreach (System.Attribute attr in attrs)
            {
                if (attr is Author)
                {
                    Author a = (Author)attr;
                    Result = a.GetInfo();
                }
            }
            return Result;
        }

    

  总结:特性除了用于描述对象信息之外,还可以与Filter(筛选器)结合实现AOP编程,具体方法详见Mvc总结-筛选器(Filter)

原文地址:https://www.cnblogs.com/hjxh/p/7867459.html