C#特性的一些用法
2021/6/25 20:27:08
本文主要是介绍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 }
结果
这篇关于C#特性的一些用法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID
- 2024-01-23用CI/CD工具Vela部署Elasticsearch + C# 如何使用
- 2024-01-23.NET开源的简单、快速、强大的前后端分离后台权限管理系统