Business Object Validation Using Attributes in C#

本文介绍了一种使用C#属性进行业务对象验证的方法。通过自定义属性实现数据验证逻辑,简化了验证过程并提高了代码可读性和可维护性。

Business Object Validation Using Attributes in C#

7/14/2009

Ok, so there are about 9,000,000 different implementations out there when it comes to validating business objects. Although most of the ones that I see out there are simply tweaked versions ofCSLA.Net. Personally I'm not a big fan of that approach. It works quite well but I just wanted to try something else, so instead I tried out the second most popular approach... Attributes. I know that usually I groan whenever I think about attributes but it actually works pretty well in this instance.

   1: public class Test
   2: {
   3:     [Between(1,4,"This item needs to be between 1 and 4")]
   4:     public int Value{get;set;}
   5: }

That's not that bad. Even if I have ten properties, that isn't that bad. And implementing the attributes themselves is simple as well:

   1: [AttributeUsage(AttributeTargets.Property,AllowMultiple=false)]
   2: public class BaseAttribute:Attribute
   3: {
   4:     public BaseAttribute(string ErrorMessage)
   5:     {
   6:         this.ErrorMessage = ErrorMessage;
   7:     }
   8:  
   9:     public string ErrorMessage { get; set; }
  10:  
  11:     internal virtual string IsValid(PropertyInfo Property,object Object)
  12:     {
  13:         return ErrorMessage;
  14:     }
  15: } 
  16:  
  17: public class Between : BaseAttribute
  18: {
  19:     public Between(object MinValue,object MaxValue, string ErrorMessage)
  20:         : base(ErrorMessage)
  21:     {
  22:         this.MinValue = MinValue;
  23:         this.MaxValue = MaxValue;
  24:     }
  25:  
  26:     public object MinValue { get; set; }
  27:     public object MaxValue { get; set; }
  28:  
  29:     internal override string IsValid(PropertyInfo Property, object Object)
  30:     {
  31:         object Value = Property.GetValue(Object, null);
  32:         if (Value is DateTime && (DateTime)Value <= DateTime.Parse(this.MaxValue.ToString()) && (DateTime)Value >= DateTime.Parse(this.MinValue.ToString()))
  33:             return "";
  34:         else if (Value is DateTime)
  35:             return ErrorMessage;
  36:         else if (double.Parse(Value.ToString()) <= double.Parse(this.MaxValue.ToString()) && double.Parse(Value.ToString()) >= double.Parse(this.MinValue.ToString()))
  37:             return "";
  38:         return ErrorMessage;
  39:     }
  40: }

That's it, a constructor, some fields to hold our information, and one function. We do however have to find the attributes and call the function to even check the property, but with a bit of reflection that's pretty simple:

   1: public static class ValidationManager
   2: {
   3:     public static bool Validate(object Object)
   4:     {
   5:         StringBuilder Builder = new StringBuilder();
   6:         if (Object != null)
   7:         {
   8:             Type ObjectType = Object.GetType();
   9:             PropertyInfo[] Properties = ObjectType.GetProperties();
  10:             foreach (PropertyInfo Property in Properties)
  11:             {
  12:                 object[] Attributes = Property.GetCustomAttributes(typeof(BaseAttribute), true);
  13:                 foreach (object Attribute in Attributes)
  14:                 {
  15:                     Builder.Append(((BaseAttribute)Attribute).IsValid(Property, Object));
  16:                 }
  17:             }
  18:         }
  19:         if(string.IsNullOrEmpty(Builder.ToString()))
  20:             return true;
  21:         throw new NotValid(Builder.ToString());
  22:     }
  23: }

That's it really. We just call the Validate function, passing in our object, and in turn  the function gets all of the properties, finds the attributes, and calls the IsValid function appropriately. And because all of our attributes inherit from BaseAttribute, all we need to do is create a new one and the function will automatically pick it up. So if we want one based off of Regex for strings, not a problem:

   1: public class Regex:BaseAttribute
   2: {
   3:     public Regex(string RegexString, string ErrorMessage)
   4:         :base(ErrorMessage)
   5:     {
   6:         this.RegexString = RegexString;
   7:     }
   8:  
   9:     public string RegexString { get; set; }
  10:  
  11:     internal override string IsValid(PropertyInfo Property, object Object)
  12:     {
  13:         object Value = Property.GetValue(Object, null);
  14:         if (Value is String)
  15:         {
  16:             System.Text.RegularExpressions.Regex TempRegex = new System.Text.RegularExpressions.Regex(RegexString);
  17:             if (TempRegex.IsMatch((string)Value))
  18:                 return "";
  19:         }
  20:         return ErrorMessage;
  21:     }
  22: }

Hell if we want to have the ability to cascade and check classes, we can:

   1: public class Cascade:BaseAttribute
   2: {
   3:     public Cascade()
   4:         : base("")
   5:     {
   6:     }
   7:  
   8:     internal override string IsValid(PropertyInfo Property, object Object)
   9:     {
  10:         object Value = Property.GetValue(Object, null);
  11:         if (Property.PropertyType.FullName.StartsWith("System.Collections.Generic.List", StringComparison.CurrentCultureIgnoreCase))
  12:         {
  13:             Type ListType = Value.GetType();
  14:             PropertyInfo IndexProperty = ListType.GetProperty("Item");
  15:             PropertyInfo CountProperty = ListType.GetProperty("Count");
  16:             int Count = (int)CountProperty.GetValue(Value, null);
  17:             for (int x = 0; x < Count; ++x)
  18:             {
  19:                 object IndexedObject = IndexProperty.GetValue(Value, new object[] { x });
  20:                 if (IndexedObject != null)
  21:                 {
  22:                     try
  23:                     {
  24:                         ValidationManager.Validate(IndexedObject);
  25:                     }
  26:                     catch (NotValid e) { return Property.Name + "(" + x + ") : " + e.Message; }
  27:                 }
  28:             }
  29:         }
  30:         else
  31:         {
  32:             if (Value != null)
  33:             {
  34:                 try
  35:                 {
  36:                     ValidationManager.Validate(Value);
  37:                 }
  38:                 catch (NotValid e) { return Property.Name + " : " + e.Message; }
  39:             }
  40:         }
  41:         return "";
  42:     }
  43: }

Heck in the one above, we can even check if this is a list and go through each item in the list... And when we're done creating the attribute, we just tack it on our properties and we're done. So try it out, leave feedback, and happy coding.

一、基础信息 数据集名称:Bottle Fin实例分割数据集 图片数量: 训练集:4418张图片 验证集:1104张图片 总计:5522张图片 分类类别: - 类别0: 数字0 - 类别1: 数字1 - 类别2: 数字2 - 类别3: 数字3 - 类别4: 数字4 - 类别5: 数字5 - 类别6: Bottle Fin 标注格式:YOLO格式,包含多边形坐标,适用于实例分割任务。 数据格式:图片格式常见如JPEG或PNG,具体未指定。 二、适用场景 实例分割AI模型开发:数据集支持实例分割任务,帮助构建能够精确识别和分割图像中多个对象的AI模型,适用于对象检测和分割应用。 工业自动化与质量控制:可能应用于制造、物流或零售领域,用于自动化检测和分类物体,提升生产效率。 计算机视觉研究:支持实例分割算法的学术研究,促进目标检测和分割技术的创新。 教育与实践培训:可用于高校或培训机构的计算机视觉课程,作为实例分割任务的实践资源,帮助学生理解多类别分割。 三、数据集优势 多类别设计:包含7个不同类别,涵盖数字和Bottle Fin对象,增强模型对多样对象的识别和分割能力。 高质量标注:标注采用YOLO格式的多边形坐标,确保分割边界的精确性,提升模型训练效果。 数据规模适中:拥有超过5500张图片,提供充足的样本用于模型训练和验证,支持稳健的AI开发。 即插即用兼容性:标注格式直接兼容主流深度学习框架(如YOLO),便于快速集成到各种实例分割项目中。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值