Attribute整理

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Runtime; 6 7 namespace reflect1 8 { 9 using System; 10 using System.Reflection; 11 12 // Define a custom attribute with one named parameter. 13 [AttributeUsage(AttributeTargets.All)] 14 public class MyAttribute : Attribute 15 { 16 private string myName; 17 public MyAttribute(string name) 18 { 19 myName = name; 20 } 21 public string Name 22 { 23 get 24 { 25 return myName; 26 } 27 } 28 } 29 30 // Define a class that has the custom attribute associated with one of its members. 31 public class MyClass1 : MyclassFather 32 { 33 [My("This is an example attribute.")] 34 public void MyMethod(int i) 35 { 36 return; 37 } 38 } 39 40 public class MyclassFather 41 { 42 public int _a; 43 public int A { 44 get{return this._a;} 45 set{this._a=value;} 46 } 47 48 protected virtual MyAttribute DataGridTypeInfo 49 { 50 get 51 { 52 var typeInfos = (MyAttribute[])GetType().GetCustomAttributes(typeof(MyAttribute), false);//取当前类,类型为MyAttribute的特性,取到MyAttribute类放入类型为MyAttribute[]数组中 53 if (typeInfos.Length != 1) throw new Exception("Missing DataGridTypeInfo attribute for " + GetType()); 54 return typeInfos[0]; 55 } 56 } 57 } 58 59 public class MemberInfo_GetCustomAttributes 60 { 61 public static void Main() 62 { 63 //MyClass1 my = new MyClass1(); 64 //my.Equals(); 65 //my.GetHashCode(); 66 //my.GetType(); 67 try 68 { 69 70 // Get the type of MyClass1. 71 Type myType = typeof(MyClass1); 72 // Get the members associated with MyClass1. 73 MemberInfo[] myMembers = myType.GetMembers(); 74 75 // Display the attributes for each of the members of MyClass1. 76 for (int i = 0; i < myMembers.Length; i++) 77 { 78 Object[] myAttributes = myMembers[i].GetCustomAttributes(typeof(System.Security.SecuritySafeCriticalAttribute), true); 79 if (myAttributes.Length > 0) 80 { 81 Console.WriteLine("\nThe attributes for the member {0} are: \n", myMembers[i]); 82 for (int j = 0; j < myAttributes.Length; j++) 83 Console.WriteLine("The type of the attribute is {0}.", myAttributes[j]); 84 } 85 } 86 } 87 catch (Exception e) 88 { 89 Console.WriteLine("An exception occurred: {0}", e.Message); 90 } 91 Console.Read(); 92 } 93 } 94 }
定义的attribute 加后缀Attribute,使用的时候名字可以不用带Attribute的后缀,如声明时候交MyAttribute用的时候只用My或者MyAttribute都可以。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决