C#特性的一些用法(1)

写在这里,以备遗忘!!!

准备一个特性类

 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     }

结果

 

posted @ 2021-06-25 18:48  只吃肉不喝酒  阅读(156)  评论(0编辑  收藏  举报