C基础 - 特性
一.特性
1>特性本质就是一个类,直接或者间接的继承了Attribute
2>特性就是在不破话类封装的前提下,加点额外的信息或者行为
特性添加后,编译会在元素内部产生IL,我们没办法直接使用,在metadata中是有的
二.应用场景之-枚举上加描述
运行结果如下图
1 using System; 2 using System.Reflection; 3 4 namespace ConsoleApp1 5 { 6 public enum RunState 7 { 8 [RemarkEnum(Remark = "正在运行")] 9 Running = 0, 10 11 [RemarkEnum(Remark = "停止")] 12 Stop = 1, 13 14 [RemarkEnum(Remark = "完成")] 15 Finish = 2, 16 } 17 class Program 18 { 19 static void Main(string[] args) 20 { 21 Console.WriteLine(RunState.Running.GetRemark()); 22 Console.WriteLine(RunState.Stop.GetRemark()); 23 Console.WriteLine(RunState.Finish.GetRemark()); 24 Console.ReadKey(); 25 } 26 } 27 public class RemarkEnumAttribute : Attribute 28 { 29 public string Remark { get; set; } 30 } 31 /// <summary> 32 /// 扩展方法:静态类,静态方法,this这三个部分造成 33 /// 调用的时候,直接对象.方法名 34 /// </summary> 35 public static class RemarkExtend 36 { 37 public static string GetRemark(this Enum enumValue) 38 { 39 Type type = enumValue.GetType(); 40 FieldInfo field = type.GetField(enumValue.ToString()); 41 if (field.IsDefined(typeof(RemarkEnumAttribute), true))//访问特性的标准流程 42 { 43 RemarkEnumAttribute attribute = (RemarkEnumAttribute)field.GetCustomAttribute(typeof(RemarkEnumAttribute), true); 44 return attribute.Remark; 45 } 46 else 47 { 48 return enumValue.ToString(); 49 } 50 } 51 } 52 }
三.应用场景值之-结构体加描述
运行结果如下图
1 using System; 2 using System.Reflection; 3 4 namespace ConsoleApp1 5 { 6 public struct CommPara 7 { 8 [StructExten(Remark = "串口号")] 9 public string CommPort; 10 [StructExten(Remark = "Id号")] 11 public int Id; 12 } 13 class Program 14 { 15 static void Main(string[] args) 16 { 17 CommPara comm = new CommPara() 18 { 19 CommPort = "Com1", 20 Id = 10, 21 }; 22 Console.WriteLine(comm.GetRemark()); 23 Console.ReadKey(); 24 } 25 } 26 27 [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Field)] 28 public class StructExtenAttribute : Attribute 29 { 30 public string Remark { get; set; } 31 } 32 public static class RemarkStructExtend 33 { 34 public static string GetRemark(this object enumValue) 35 { 36 string Name = string.Empty; 37 Type type = enumValue.GetType(); 38 FieldInfo[] fields = type.GetFields(); 39 foreach (var field in fields) 40 { 41 if (field.IsDefined(typeof(StructExtenAttribute), true)) 42 { 43 StructExtenAttribute attribute = (StructExtenAttribute)field.GetCustomAttribute(typeof(StructExtenAttribute), true); 44 Name += $"{ attribute.Remark},"; 45 } 46 else 47 { 48 Name = enumValue.ToString(); 49 } 50 } 51 return Name; 52 } 53 } 54 }
四.访问类,属性,方法上的特性,另外特性上加一些验证行为
调用实例如下:
首先控制台项目中,添加Student类,Manager类,Validate特性类,这些类见下面,添加好后如下图显示的:
1 using System; 2 3 namespace _002_Attribute 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 try 10 { 11 Student student = new Student() 12 { 13 Name = "小王", 14 Id = 100, 15 QQ = 10002, 16 }; 17 Manager.Show<Student>(student); 18 Console.ReadKey(); 19 } 20 catch (Exception ex) 21 { 22 23 } 24 } 25 } 26 }