C# 特性类[笔记]

tech2025-12-20  10

C# 特性类[笔记]

Attribute(自定义特性类)声明自定义特性类使用自定义特性类 Conditional阐述使用 Obsolete附加[Authorize]

Attribute(自定义特性类)

声明自定义特性类

表示目标结构的状态添加一个类,以Attribute结尾这个类继承 system.Attribute声明为私有类(sealed)定义需要描述的字段和属性AttributeUsage() 里面的值为该特性可以应用到那些结构上 AttributeTargets为枚举类型 [AttributeUsage(AttributeTargets.Class)]//声明标识结构 sealed class mytestAttribute : System.Attribute//继承 { public string Id { get; set; } public string name { get; set; } public string age { get; set; } public string sex { get; set; } public mytestAttribute(string str) { this.name = str; } }

使用自定义特性类

[AttributeUsage(AttributeTargets.Method)] 标识一个方法

使用特性类 [特性类名] 这里注意的是,程序会自动忽略掉程序名后面的Attribute给特性类属性赋值: 1.构造函数 2.通过参数名赋值 [mytest("我是名字",Id ="12")] class TestClass { } //访问方法应用的特性 public static void Test2() { Type type = typrof(TestClass); //获取特性对象 object[] array= type.GetCustomAttributes(false);//是否继承类的texing //转化为特性类 mytestAttribute mytest = array[0] as mytestAttribute; //输出特性信息 Console.WriteLine(mytest.name); Console.WriteLine(mytest.Id); }

Conditional

阐述

[Conditional]: 标记之后,调试代码不进入此方法进行调试

使用

标识方法需要通过定义一个宏来控制(define) 存在则进行调试,不存在不进行调试 #define def //方法将进行调试 using System; using System.Diagnostics; [Conditional("def")] public static void Test() { }

Obsolete

标识方法是否被弃用

1.参数一(string):报错信息 2.参数二(bool):是否报错

//提示信息 “方法被弃用”,只产生警告 [Obsolete("方法被弃用")]//方法被弃用 static void OldMethod(string str) { Console.WriteLine(str); } //提示信息 “方法被弃用”,产生报错 [Obsolete("方法被弃用",true)]//方法被弃用 static void OldMethod(string str) { Console.WriteLine(str); }

附加

[Authorize]

权限验证特性 需配合Token使用

最新回复(0)