翼度科技»论坛 编程开发 .net 查看内容

.NET中特性+反射 实现数据校验

10

主题

10

帖子

30

积分

新手上路

Rank: 1

积分
30
.NET中特性+反射 实现数据校验

在.NET中,我们可以使用特性+反射来实现数据校验。特性是一种用于为程序中的代码添加元数据的机制。元数据是与程序中的代码相关联的数据,但不直接成为代码的一部分。通过特性,我们可以为类、方法、属性等添加额外的信息,这些信息可以在运行时通过反射获取和使用。
对反射不太熟悉的小伙伴可以去看我以前的文章 .NET中的反射
为了实现数据校验,我们可以定义一个自定义特性,并将其应用于需要校验的属性或参数上。然后,我们可以编写代码来检查这些特性,并根据特性的配置执行相应的校验逻辑。
示例代码

定义自定义特性
  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
  4. public class ValidationAttribute : Attribute
  5. {  
  6.     public string ErrorMessage { get; set; }
  7.   
  8.     public ValidationAttribute(string errorMessage)  
  9.     {  
  10.         ErrorMessage = errorMessage;  
  11.     }
  12. }
复制代码
定义具体的校验特性
  1. [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
  2. public class RequiredAttribute : ValidationAttribute  
  3. {  
  4.     public RequiredAttribute() : base("该字段是必填项。") { }  
  5. }  
  6.   
  7. [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
  8. public class RangeAttribute : ValidationAttribute  
  9. {  
  10.     public int Minimum { get; set; }  
  11.     public int Maximum { get; set; }
  12.   
  13.     public RangeAttribute(int minimum, int maximum, string errorMessage = "该字段的值必须在 {0} 和 {1} 之间。")   
  14.         : base(errorMessage)  
  15.     {  
  16.         Minimum = minimum;  
  17.         Maximum = maximum;  
  18.     }
  19. }
复制代码
在模型类中使用这些特性
  1. public class Person  
  2. {  
  3.     [Required]
  4.     public string Name { get; set; }
  5.   
  6.     [Range(18, 100, ErrorMessage = "年龄必须在 18 到 100 之间。")]
  7.     public int Age { get; set; }
  8. }
复制代码
编写验证方法
  1. public class Validator  
  2. {  
  3.     public static bool Validate<T>(T obj, out string errorMessage)  
  4.     {  
  5.         errorMessage = null;  
  6.         var type = typeof(T);  
  7.         var properties = type.GetProperties();  
  8.   
  9.         foreach (var property in properties)  
  10.         {  
  11.             var validationAttributes = property.GetCustomAttributes(typeof(ValidationAttribute), true);  
  12.   
  13.             foreach (var attribute in validationAttributes)  
  14.             {  
  15.                 var value = property.GetValue(obj);  
  16.   
  17.                 switch (attribute)  
  18.                 {  
  19.                     case RequiredAttribute required:  
  20.                         if (value == null || (value is string str && string.IsNullOrWhiteSpace(str)))  
  21.                         {  
  22.                             errorMessage = required.ErrorMessage;  
  23.                             return false;  
  24.                         }  
  25.                         break;  
  26.                     case RangeAttribute range:  
  27.                         if (value is IComparable comparable)  
  28.                         {  
  29.                             if (comparable.CompareTo(range.Minimum) < 0 || comparable.CompareTo(range.Maximum) > 0)  
  30.                             {  
  31.                                 errorMessage = string.Format(range.ErrorMessage, range.Minimum, range.Maximum);  
  32.                                 return false;  
  33.                             }  
  34.                         }  
  35.                         break;  
  36.                     // 可以添加更多校验特性类型  
  37.                 }  
  38.             }  
  39.         }  
  40.   
  41.         return true;  
  42.     }  
  43. }
复制代码
使用Validator类来校验Person对象
  1. class Program
  2. {
  3.     static void Main(string[] args)
  4.     {
  5.         var person = new Person { Name = "张三", Age = 15 };
  6.         string errorMessage;
  7.         bool isValid = Validator.Validate(person, out errorMessage);
  8.         if (!isValid)
  9.         {
  10.             Console.WriteLine(errorMessage); // 输出:该字段是必填项。
  11.         }
  12.         Console.ReadLine();
  13.     }
  14. }
复制代码
说明

这个示例演示了如何使用特性和反射实现基本的数据校验。在实际应用中,你可能需要处理更复杂的校验逻辑和更多的校验类型。
此外,还可以使用现有的数据特性(如System.ComponentModel.DataAnnotations命名空间中的特性)来简化校验过程。
以下是该命名空间中一些常用的特性(Attribute),以及它们的用途:
[table][tr]特性名称用途[/tr][tr][td][Required][/td][td]确保属性值不为空(不为 null 且对于字符串不是空字符串)。[/td][/tr][tr][td][StringLength][/td][td]限制字符串属性的最大长度。[/td][/tr][tr][td][Range][/td][td]确保数值型属性在指定的范围内。[/td][/tr][tr][td][Minimum][/td][td]确保数值型属性不小于指定的最小值。[/td][/tr][tr][td][Maximum][/td][td]确保数值型属性不大于指定的最大值。[/td][/tr][tr][td][RegularExpression][/td][td]通过正则表达式验证属性值的格式。[/td][/tr][tr][td][EmailAddress][/td][td]验证属性值是否为有效的电子邮件地址。[/td][/tr][tr][td]https://www.cnblogs.com/cqai/p/1 ... com/cqai/p/18203814
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具