标签:color button form zed test special threading rac text
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Text; 7 using System.Reflection; 8 using System.Windows.Forms; 9 10 11 using System.Threading; 12 13 using System.Collections.Specialized; 14 15 namespace Test123 16 { 17 public partial class Form1 : Form 18 { 19 20 public Form1() 21 { 22 InitializeComponent(); 23 } 24 25 private void Form1_Load(object sender, EventArgs e) 26 { 27 28 } 29 30 public class TestAttri : Attribute 31 { 32 public string JJ { get; set; } 33 } 34 35 [TestAttri(JJ = "8899")] 36 public class ClassTest2 : ClassTest { } 37 38 public abstract class ClassTest { } 39 40 private void button3_Click(object sender, EventArgs e) 41 { 42 ClassTest obj = new ClassTest2(); 43 Type type = obj.GetType(); 44 TestAttri att = GetCustomAttribute<TestAttri>(type, false); 45 //(TestAttri)type.GetCustomAttributes(typeof(TestAttri), false).GetValue(0); 46 //或者 (TestAttri)obj.GetType().GetCustomAttributes(typeof(TestAttri), false)[0]; 47 att.JJ = "rich"; 48 49 //需要特别注意的地方: 50 //GetCustomAttributes 方法每次都返回新的实例 51 //每次获取 io 的 CustomAttributes 都是一个新的副本 52 53 MessageBox.Show(att.JJ); 54 55 ((TestAttri)obj.GetType().GetCustomAttributes(typeof(TestAttri), false)[0]).JJ = "jigjig"; 56 MessageBox.Show(((TestAttri)obj.GetType().GetCustomAttributes(typeof(TestAttri), false)[0]).JJ); 57 } 58 59 private static Dictionary<MemberInfo, Object> _dicCache1 = new Dictionary<MemberInfo, Object>(); 60 private static Dictionary<MemberInfo, Object> _dicCache2 = new Dictionary<MemberInfo, Object>(); 61 62 public static TAttribute[] GetCustomAttributes<TAttribute>(MemberInfo member, Boolean inherit) 63 { 64 if (member == null) 65 { 66 return new TAttribute[0]; 67 } 68 69 // 根据是否可继承,分属两个缓存集合 70 var cache = inherit ? _dicCache1 : _dicCache2; 71 72 Object obj = null; 73 if (cache.TryGetValue(member, out obj)) 74 { 75 return (TAttribute[])obj; 76 } 77 lock (cache) 78 { 79 if (cache.TryGetValue(member, out obj)) 80 { 81 return (TAttribute[])obj; 82 } 83 var atts = member.GetCustomAttributes(typeof(TAttribute), inherit) as TAttribute[]; 84 var att = atts == null ? new TAttribute[0] : atts; 85 cache[member] = att; 86 return att; 87 } 88 } 89 90 public static TAttribute GetCustomAttribute<TAttribute>(MemberInfo member, Boolean inherit) 91 { 92 var atts = member.GetCustomAttributes<TAttribute>(inherit); 93 if (atts == null || atts.Length < 1) 94 { 95 return default(TAttribute); 96 } 97 return atts[0]; 98 } 99 100 } 101 102 }
obj.GetType().GetCustomAttributes
标签:color button form zed test special threading rac text
原文地址:https://www.cnblogs.com/wang_xy/p/12050593.html