C#通过特性验证实体属性值

一,什么是特性

特性也是一种对象,特殊之处在于其编译时就存在了,也就是在程序运行之前就存在了。

二,如何定义一个特性

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
    public sealed class RequiredAttribute:Attribute
    {
        public  bool Validate(object value)
        {
            if (value == null) return true;
            if (string.IsNullOrEmpty(value.ToString())) return true;
            if (string.IsNullOrWhiteSpace(value.ToString())) return true;
            return false;
        }
    }

三,特性验证实体属性正确性

  • 定义特性基类
/// <summary>
    /// 数据特性验证的基类
    /// </summary>
    public abstract class AbstractValidateAttribute : Attribute
    {
        public abstract bool Validate(object value);
    }
数据特性验证的基类
  • 实现NullEmpty特性
 [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
    public sealed class NullEmptyAttribute : AbstractValidateAttribute
    {
        public override bool Validate(object value)
        {
            if (null == value) return true;
            return string.IsNullOrEmpty(value.ToString());
        }
    }
  • 实现Validate扩展方法
 1  public static class AttributeExtend
 2     {
 3         public static void Validate<T>(this T tModel) where T : new()
 4         {
 5             Type type = tModel.GetType();
 6             foreach (var prop in type.GetProperties())
 7             {
 8                 if (prop.IsDefined(typeof(AbstractValidateAttribute), true))
 9                 {
10                     object[] attributeArray = prop.GetCustomAttributes(typeof(AbstractValidateAttribute), true);
11                     foreach (AbstractValidateAttribute attribute in attributeArray)
12                     {
13                         if (attribute.Validate(prop.GetValue(tModel, null)))
14                         {
15                             //return true;//表示终止
16                             throw new Exception(string.Format("{0}的值不可为{1}", prop.Name, prop.GetValue(tModel, null) == null ? "null" : prop.GetValue(tModel, null).ToString()));
17                         }
18                     }
19                 }
20             }
21             //return false;
22         }
23 
24 
25     }
  • 定义实体并使用NullEmpty特性
1  public class Student
2     {
3         public int Id { get; set; }
4         [NullEmpty]
5         public string Name { get; set; }
6     }
  • 调用验证方法
 1            try
 2             {
 3                 Student _Student = new Student();
 4                 _Student.Validate();
 5             }
 6             catch (Exception ex)
 7             {
 8                 Console.WriteLine(ex.Message);
 9             }
10            
11             Console.ReadKey();

显示结果:

 源码GitHub:        https://github.com/founshi/AttributeDemo

原文地址:https://www.cnblogs.com/ErricShih/p/10249980.html