【C#】特性复习

  • 特性(attribute)是一种允许我们向程序的程序集增加元数据的语言结构。它用于保存程序结构信息的某种特殊类型的类。

Obsolete提示程序员 某些函数方法已经过时

class Program
    {
        [Obsolete("这个方法过时了,请使用NewMethod")]
        static void OldMethod()
        {
            Console.WriteLine("This is OldMethod");
        }
        static void NewMethod()
        {

        }
        static void Main(string[] args)
        {
            OldMethod();
            Console.ReadKey();
        }
    }

Conditional特性 带有一个参数,编译器编译时会检测是否有一个编译符号被定义为此参数,如果定义了就照常执行,反之就不会执行

        class Program
    {
        
        [Conditional("isTest")]//isTest就是编译符号 
        static void Test1()
        {
            Console.WriteLine("Test1");
        }
        static void Test2()
        {
            Console.WriteLine("Test2");
        }
        
        static void Main(string[] args)
        {
            Test1();
            Test2();
            Test1();
            Console.ReadKey();
        }
    }

这段代码由于没有isTest编译符,所以程序执行时只执行了Test2()方法
要让其运行只需在要脚本的第一行添加宏定义即可

# define isTest

调用者信息特性可以访问文件路径、代码行数、调用成员的名称等源代码信息。这三个特性名称为CallerFilePath、CallerLineNumber和CallerMemberName

例如:

public static void MyTrace(string message,[CallerFilePath] string fileName="",[CallerLineNumber] int lineNumber=0,[CallerMemberName] string callingMember=""){}

输出fileName、lineNumber、callingMember即可查看函数调用信息


DebuggerStepThrough特性告诉调试器在执行目标代码时不要进入该方法调试。

要注意以下两点:
该特性位于System.Diagnostics命名空间;
该特性可用于类、结构、构造函数、方法或访问器。


自定义特性

    [AttributeUsage(AttributeTargets.Class)]//创建的自定义特性适用范围是类
    public sealed class MytestAttribute :System.Attribute
    {
        public string Description { get; set; }
        public int ID { get; set; }

        public MytestAttribute(string description,int id)
        {
            this.Description = description;
            this.ID = id;
        }
    }
    [Mytest("这是我的特性",100)]//实际使用时会帮我们自动省去Attribute字符串
    class Program

可以输出特性结构的成员变量

        static void Main(string[] args)
        {
            Type myType = typeof(Program);//可以使用typeof获取类里的Type对象
            Object[] objects= myType.GetCustomAttributes(false);//false表示不会获取继承Program类的特性
            MytestAttribute mytest = objects[0] as MytestAttribute;//我们这里只有一个Program类用到了自定义特性 所以使用objects[0]
            Console.WriteLine(mytest.ID);
            Console.WriteLine(mytest.Description);
            Console.ReadKey();
        }

猜你喜欢

转载自blog.csdn.net/wangjianxin97/article/details/88387692