NET 特性(Attribute)
特性(Attribute):是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。
您可以通过使用特性向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。
特性(Attribute)用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。
.Net 框架提供了两种类型的特性:预定义特性和自定义特性。
1.自定义特性:Net 框架允许创建自定义特性,用于存储声明性的信息,且可在运行时被检索。该信息根据设计标准和应用程序需要,可与任何目标元素相关。
创建并使用自定义特性包含四个步骤:
- 声明自定义特性
- 构建自定义特性
- 在目标程序元素上应用自定义特性
- 通过反射访问特性
/// <summary> /// 别名特性 /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] public class AliasAttribute : Attribute { /// <summary> /// 别名 /// </summary> public string Name { get; set; } /// <summary> /// 别名类型 /// </summary> public Type Type { get; set; } /// <summary> /// 别名名称,类型默认为string /// </summary> /// <param name="name"></param> public AliasAttribute(string name) { Name = name; Type = typeof(string); } /// <summary> /// 别名名称,类型为传入类型 /// </summary> /// <param name="name"></param> public AliasAttribute(string name, Type type) { Name = name; Type = type; } }
2.在目标程序元素上应用自定义特性
public class UserDto { /// <summary> /// 姓名 /// </summary> [Alias("name", typeof(string))] public string Name { get; set; } /// <summary> /// 电话 /// </summary> [Alias("phone", typeof(string))] public string Phone { get; set; } /// <summary> /// 备注 /// </summary> [Alias("remark", typeof(string))] public string Remark { get; set; } }
3.通过反射访问特性
// 获取type var userType = typeof(UserDto); // 获取类中所有公共属性集合 var PropertyArr = userType.GetProperties(); foreach (var itemProperty in PropertyArr) { // 获取属性上存在AliasAttribute的数组 var customAttributesArr = itemProperty.GetCustomAttributes(typeof(AliasAttribute), true); if (customAttributesArr.Any()) { // 获取特性 var first = customAttributesArr.FirstOrDefault(); } else { // 不存在特性 } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现