C#--特性基础

以下是学习笔记:

泛型:把类型做到通用,最终目的是可以动态编程

反射:读取DLL文件描述信息的一个类库

特性:贴标签,贴上标签后就产生了新的功能

一,认识特性

特性:1,是一个类。2,继承自Attribute。满足这2个就是特性。

目前哪些地方是使用到了特性:几乎所有的框架都用到了,MVC,WebApi, EF,IOC,AOP

特性使用场景:数据验证,授权

1,数据验证:

举例1:

 说明:

[Required]:这个属性不能为空,不输入值就报错

[Disaply(Name=“电子邮件”)]:这个属性自动显示名字:“电子邮件”

举例2:

说明:

 [EmailAddress]:验证电子邮件地址

举例3:

 说明:

还能指定数据类型

2,授权

说明: 

这是一个授权的,标注了这个属性【Authorize】,下面的这个方法才能用。

二,特性分类

1,系统自带特性

[DebuggerStepThrough]:不让调试

[Obsolete]:已过时的

有一些是影响到了编译器的运行

2,自定义的

举例:系统自带的特性

        #region 系统自带的特性
        
        [Obsolete("这个方法过时了,使用NewMedthod代替",false)]//Obsolete用来表示一个方法被弃用了,参数1是字符串提示的,参数2,true或false(true是错误,false是警告)
        //如果参数2是true ,运行 OldMedthod()就报错啦
        static void OldMedthod()
        {
            Console.WriteLine("旧方法");
        }
        static void NewMedthod()
        {
            Console.WriteLine("新方法");
        }

        [Conditional("IsTest")]//Conditional特性,这个方法不会被调用了。#define IsTest//定义了一个宏,在using前面加这一行,就可以继续使用
        static void Test1()
        {
            Console.WriteLine("test1");
        }
        static void Test2()
        {
            Console.WriteLine("test2");
        }

        [DebuggerStepThrough]//可以掉过debugger的单步调试,不让进入该方法(当我们确定这个方法没有任何错误的时候可以使用这个特性)
        static void PrintOut(string str,[CallerFilePath]string fileName="",[CallerLineNumber]int lineNumber=0,[CallerMemberName]string methodName="")
        {
            Console.WriteLine(str);
            Console.WriteLine(fileName);//文件路径
            Console.WriteLine(lineNumber);//代码行数
            Console.WriteLine(methodName);//调用成员的名称
        }

        #endregion

  

三,创建特性

要把DefidAttribute看出是一个普通的类,里面可以写字段,方法,属性,,,

四,特性调用

1,创建特性:

//自定义Attribute
    [AttributeUsage(AttributeTargets.Class,AllowMultiple=false,Inherited=false)]
    //参数1:可以被哪些情况下使用,如果是All就是被所有情况下都可以用。
    //参数2:是否可以放多次
    //参数3:是否被继承
   
    public class HelpAttribute:Attribute
    {
        protected string description;
        public HelpAttribute(string description_in)
        {
            this.description = description_in;
        }

        public string Description
        {
            get { return this.description; }
        }
    }

    //调用自定义的Attribute
    //[Help("this is a do-nothing class")]//调用特性方法1:
    [HelpAttribute("this is a do-nothing class")]//调用特性方法2:写上全称也可以
    public class AnyClass
    {

    }

  

2,特性调用:

            #region 通过反射来获取Attribute中的信息
            Console.WriteLine("------------通过反射来获取Attribute中的信息-------------");
            HelpAttribute helpAttribute;
            foreach (var item in typeof(AnyClass).GetCustomAttributes(true))
            {
                helpAttribute = item as HelpAttribute;
                if (helpAttribute != null)
                {
                    Console.WriteLine("AnyClas Description:{0}", helpAttribute.Description);
                }
            }
            #endregion

  

结果:AnyClas Description:this is a do-nothing class

原文地址:https://www.cnblogs.com/baozi789654/p/14227336.html