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

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

weixin_33796205

一,什么是特性

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

二,如何定义一个特性

[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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值