C#特性是一种代码标记信息,这中信息可以从外部读取。[attribute].
示例代码如下:
- //创建特性 AllowMultiple允许多次使用,AttributeUsage应用到什么类型的目标 AttributeTargets构造函数参数值
- [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,AllowMultiple =false)]
- public class DoesInterestingThingsAttribute : Attribute {//通过继承Attribute来创建自定义特性
- public DoesInterestingThingsAttribute(int howManyTimes) {
- HowManyTimes = howManyTimes;
- }
- public int HowManyTimes {
- get;private set;
- }
- public string WhateDoesItDo { get; set; }
- }
- //自定义特性 //系统特性
- [DoesInterestingThingsAttribute(1000, WhateDoesItDo = "voodoo")][DebuggerStepThrough]//类的特性
- public class DecoratedClass {
- [DebuggerStepThrough]//方法特性
- public void DullMethod() { }
- }
- //特性的读取,通过反射(reflection)技术。
- public static void Main(string[] args){
- //特性读取 类的特性读取
- Type classType = typeof(DecoratedClass);
- object[] customAttributes = classType.GetCustomAttributes(true);
- foreach (object cuestomAttritute in customAttributes)
- {
- Console.WriteLine($"找到特性:={cuestomAttritute}");
- if (cuestomAttritute is DoesInterestingThingsAttribute aa)
- {
- Console.WriteLine($"This class does {aa.WhateDoesItDo}***" + $" {aa.HowManyTimes}!");
- }
- else
- {
- Console.WriteLine("不是自定义特性");
- }
- }
- //方法的特性读取
- MethodInfo method = classType.GetMethod(nameof(DecoratedClass.DullMethod));
- object[] DullMethodAttributes = method.GetCustomAttributes(true);
- foreach (object item in DullMethodAttributes)
- {
- if (item is DebuggerStepThroughAttribute)
- {
- Console.WriteLine("找到方法特性:={0}", item.ToString());
- }
- }
- }

本文深入讲解了C#中的特性(Attribute)概念,包括如何自定义特性、应用特性于类和方法,以及如何通过反射技术读取特性信息。通过示例代码展示了特性在实际开发中的应用。
810

被折叠的 条评论
为什么被折叠?



