特性类的使用过程:
第一步:定义一个特性类,定义一些成员来包含验证时需要的数据;
第二步:创建特性类实例;
创建一个特性类的实例,里面包含着验证某一个属性或者字段需要的数据。
将该实例关联到某个属性上面。
第三步:使用特性类实例
可以通过调用某个类型的GetProperties()方法,获取属性,
然后调用类型属性成员的GetCustomAttributes()方法,获取该属性关联的特性类实例,
然后使用查找到的特性类实例验证新建对象。
第二步:创建一个特性类的实例,并关联一个属性
public class Order { [StringLength("订单号", 6, MinLength = 3, ErrorMessage = "{0}的长度必须在{1}和{2}之间!")]//实例化一个特性类,关联到一个字段上面 public string OrderID { get; set; } }
第三步:使用特性类实例,进行验证
class Program { #region 使用特性类的过程 //验证过程 //1.通过映射,找到成员属性关联的特性类实例, //2.使用特性类实例对新对象的数据进行验证 //用特性类验证订单号长度 public static bool isIDLengthValid(int IDLength, MemberInfo member) { foreach (object attribute in member.GetCustomAttributes(true)) //2.通过映射,找到成员属性上关联的特性类实例, { if (attribute is StringLengthAttribute)//3.如果找到了限定长度的特性类对象,就用这个特性类对象验证该成员 { StringLengthAttribute attr = (StringLengthAttribute)attribute; if (IDLength < attr.MinLength || IDLength > attr.MaxLength) { string displayName = attr.DisplayName; int maxLength = attr.MaxLength; int minLength = attr.MinLength; string error = attr.ErrorMessage; Console.WriteLine(error, displayName,maxLength, minLength);//验证失败,提示错误 return false; } else return true; } } return false; } //验证订单对象是否规范 public static bool isOrderValid(Order order) { if (order == null) return false; foreach (PropertyInfo p in typeof(Order).GetProperties()) { if (isIDLengthValid(order.OrderID.Length, p))//1记录下新对象需要验证的数据, return true; } return false; } #endregion public static void Main() { Order order=new Order(); do { Console.WriteLine("请输入订单号:"); order.OrderID= Console.ReadLine(); } while (!isOrderValid(order)); Console.WriteLine("订单号输入正确,按任意键退出!"); Console.ReadKey(); } }
总结:特性类的实例里没有验证逻辑,只有验证用到的规范数据(比如字符串长度)、提示信息等。验证逻辑需要自己写。
标签:
C# 特性(Attribute)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!