C#记录六——特性

特性

是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。您可以通过使用特性向程序添加声明性信息。

obsolete特性

表示方法被弃用,但是仍然可以使用

        //后面的括号内表示提醒的内容,当鼠标放到应用的地方的时候,会有提示出现
        //第二个参数,bool类型,如果设置为true,那么这个方法将无法应用了,直接报错
        [Obsolete("这个方法过时了,新方法为NewMethod",false)]
        static void OldMethod()
        {
            Console.WriteLine("OldMethod");
        }
        static void NewMethod()
        {
            Console.WriteLine("NewMethod");
        }

conditional特性

使用头文件 using System.Diagnostics

        //如果想取消Test1这个方法的调用
        //如果IsTest这个字符串是否定义过,如果定义了,就调用
        //#define IsTest//定义一个宏
        [Conditional("IsTest")]
        static void Test1()
        {
            Console.WriteLine("TEST1");
        }
        static void Test2()
        {
            Console.WriteLine("TEST2");
        }

调用者信息特性

使用头文件 using System.Runtime.CompilerServices;

        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);
        }

DebuggerStepThrough特性

知道某些方法不可能出错,跳过某些方法的调试,单步

        [DebuggerStepThrough]
        static void Debugger()
        {
            Console.WriteLine("Debugger");
        }

自定义特性类

就是一个类,叫做特性类

    //1、特性类的后缀以Attribute结尾
    //2、继承自system.Attribute
    //3、特性类一般情况下不需要被继承,设置为sealed
    //4、一般情况下特性类用来表示目标结构的一些状态(定义字段或者属性,不定义方法)

    [AttributeUsage(AttributeTargets.Class)]//表示使用目标,可以运用到的程序结构有哪些,使用到类
    sealed class MyTestAttribute:System.Attribute
    {
        public string Description { get; set; }
        public string VersionNumber { get; set; }
        public int ID { get; set; }
        public MyTestAttribute(string des)
        {
            this.Description = des;
        }
    }

//使用
    [MyTest("简单的特性类",ID = 100)]
    class Program
    {
    }

上述特性的使用

        static void Main(string[] args)
        {
            OldMethod();
            Test1();
            Test2();
            Test1();
            Test1();
            Debugger();
            PrintOut("123");

            Type type = typeof(Program);//通过typeof+类名获取type对象
            object[] array=  type.GetCustomAttributes(false);//参数,表示是否搜索父类的特性
            foreach(var temp in array)
            {
                Console.WriteLine(temp);
            }

            MyTestAttribute mytest = array[0] as MyTestAttribute;
            Console.WriteLine(mytest.Description);
            Console.WriteLine(mytest.ID);

            Console.ReadKey();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值