1. 程式人生 > 其它 >C#特性的一些用法

C#特性的一些用法

寫在這裡,以備遺忘!!!

準備一個特性類

 1 [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
 2     internal class NickNameAttribute : Attribute
 3     {
 4         public string NickName { get; set; }
 5 
 6         public NickNameAttribute(string nickName)
 7         {
 8             this.NickName = nickName;
9 } 10 }

準備一個普通類 在屬性上面加了特性

public class Test
    {
        [NickName("大寫簡稱")]
        public string CName { get; set; }

        [NickName("簡稱")]
        [NickName("無意義簡稱")]
        public string Name { get; set; }

        [NickName("小寫簡稱")]
        public string TName { get; set; }
    }

準備一個獲取特性的方法類

 1 public class NickNameAttributeHelper
 2     {
 3         /// <summary>
 4         /// 獲取特定特性的方法,可改寫成泛型方法
 5         /// </summary>
 6         /// <param name="obj"></param>
 7         /// <returns></returns>
 8         public static List<string> GetPropertyAtrribute(object
obj) 9 { 10 var list = new List<string>(); 11 12 var type = obj.GetType(); 13 var properties = type.GetProperties();//獲取所有的屬性 14 foreach (var property in properties) 15 { 16 if (property.IsDefined(typeof(NickNameAttribute), true))//判定屬性是否定義了特定特性 17 { 18 var propertyName = property.Name + "-"; 19 var attributes = property.GetCustomAttributes(typeof(NickNameAttribute), true);//獲取當前屬性上面的指定特性 20 string value = default; 21 foreach (NickNameAttribute item in attributes) 22 { 23 value += item.NickName + "-"; 24 } 25 propertyName += value; 26 list.Add(propertyName); 27 } 28 } 29 30 return list; 31 } 32 }

執行

 1 internal class Program
 2     {
 3         private static void Main(string[] args)
 4         {
 5             var test = new Test();
 6 
 7             var attributeValues = NickNameAttributeHelper.GetPropertyAtrribute(test);
 8 
 9             attributeValues.ForEach(a => Console.WriteLine($"{a}"));
10         }
11     }

結果