me2day中文版,大学生新闻网,森美老婆
转自 博客园(fish)
特性(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 { // 不存在特性 } }
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Net Core Web Api项目与在NginX下发布的方法
asp.net core3.1 引用的元包dll版本兼容性问题解决方案
IdentityServer4实现.Net Core API接口权限认证(快速入门)
ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径的实现
网友评论