对System.ComponentModel.DataAnnotations 的学习应用
摘要
你还在为了验证一个Class对象中很多数据的有效性而写很多If条件判断吗?我也同样遇到这种问题,不过,最近学了一项新的方法,让我不在写很多if条件做判断,通过给属性标注特性来验证数据规则,从此再也不需要写很多If条件判断了。
最近写C#项目中的时候,在验证数据的有效性的时候写了很多判断,结果工作量很大,然后就想能实现在类属性上标示验证的特性,来验证数据的有效性,以前听说过,但是从来没有实现过,也很少看到在项目中别人使用过,所以就一直没有研究过,但是最近在写Model的时候需要验证很多数据的有效性,所以就想研究一下。
需求:将类属性标示一个验证特性,在使用该类的时候验证数据的有效性,
我是使用了控制台应用程序做测试,首先我的思路是将Class的属性标示上特性,用来验证属性的数据规则,
这里定义了一个验证特性,主要是来标示属性的最大长度,和当大于最大长度是得提示信息。
/// <summary>
/// 指定数据字段中允许的最小和最大字符长度。
/// </summary>
public class StringLengthAttribute : Attribute
{
/// <summary>
/// 获取或设置字符串的最大长度。
/// </summary>
public int MaximumLength { get; set; }/// <summary>
/// 消息提示
/// </summary>
public string ErrorMessage { get; set; } /// <summary>
///
/// </summary>
/// <param name="maximumLength"></param>
public StringLengthAttribute(int maximumLength)
{
MaximumLength = maximumLength;
} }
这里是用来验证的类
/// <summary>
/// 数据模型
/// </summary>
public class DataModel : MyIsValid<DataModel>
{
/// <summary>
/// 值
/// </summary>
[StringLength(, ErrorMessage = "Value最大长度为5")]
public string Value { get; set; }
}
然后我就写了一个基类,统统的在基类中做验证。下面是基类的代码,打算以后所有的需要做验证的类,都继承该基类,将属性标识上特性做验证呢(后来发现更好的办法),写的不好,还请多多指教。
public class MyIsValid<T> where T : class
{ //验证信息
internal string Msg { get; set; } // 验证是否有效
internal bool IsValid()
{
var v = this as T; Type type = v.GetType(); PropertyInfo[] propeties = type.GetProperties();
foreach (PropertyInfo property in propeties)
{
List<Attribute> attributes = property.GetCustomAttributes().ToList(); var propertyValue = property.GetValue(v); Attribute stringlength = attributes.FirstOrDefault(p => p.GetType().IsAssignableFrom(typeof(StringLengthAttribute))); if (stringlength == null)
continue; int length = ((StringLengthAttribute)stringlength).MaximumLength; string currentValue = (string)propertyValue; if (currentValue.Length > length)
{
Msg = ((StringLengthAttribute)stringlength).ErrorMessage;
return false;
}
}
return true;
}
}
然后执行结果如图:

执行结果还行,只不过还需要对基类做扩展,支持针对不同的特性做不同的验证。
然后我想到了Asp.Net MVC 里面使用的数据模型绑定技术,然后就想能不能使用它的现有的方法,后来就发现了,“System.ComponentModel.DataAnnotations”这个
具体参考:https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validator.aspx
然后针对我的需求写了一个扩展方法,如下.(注意一定要引用:System.ComponentModel.DataAnnotations;)
public static class ExtensionHelper
{
/// <summary>
/// 验证对象是否有效
/// </summary>
/// <param name="obj">要验证的对象</param>
/// <param name="validationResults"></param>
/// <returns></returns>
public static bool IsValid(this object obj, Collection<ValidationResult> validationResults)
{
return Validator.TryValidateObject(obj, new ValidationContext(obj, null, null), validationResults, true);
} /// <summary>
/// 验证对象是否有效
/// </summary>
/// <param name="obj">要验证的对象</param>
/// <returns></returns>
public static bool IsValid(this object obj)
{
return Validator.TryValidateObject(obj, new ValidationContext(obj, null, null), new Collection<ValidationResult>(), true);
}
}
使用方式如下:
验证相关特性:https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx
也可以自定义,
class Program
{
static void Main(string[] args)
{
DataModel r = new DataModel(); r.EmailAddress = "cdaimesdfng1m"; var v = new Collection<ValidationResult>(); if (r.IsValid(v))
{
Console.WriteLine("");
}
else
{
v.ToList().ForEach(e =>
{
Console.WriteLine(e.ErrorMessage);
});
} Console.ReadKey();
}
} public class DataModel
{
/// <summary>
///
/// </summary>
[Required]
[StringLength(, ErrorMessage = "太大")]
public string Name { get; set; } /// <summary>
///
/// </summary>
[Range(, )]
public string d { get; set; } /// <summary>
///
/// </summary>
[EmailAddress]
public string EmailAddress { get; set; }
}
Demo下载地址:http://download.csdn.net/detail/u014265946/9330181
对System.ComponentModel.DataAnnotations 的学习应用的更多相关文章
- System.ComponentModel.DataAnnotations 冲突
项目从原来的.NET Framework4.0 升级到 .NET Framework4.5 编译报错. 查找原因是: Entity Framework 与 .net4.5 的 System.Compo ...
- System.ComponentModel.DataAnnotations.Schema.TableAttribute 同时存在于EntityFramework.dll和System.ComponentModel.DataAnnotations.dll中
Entity Framework 与 .net4.5 的 System.ComponentModel.DataAnnotations 都有 System.ComponentModel.DataAnno ...
- System.ComponentModel.DataAnnotations.Schema 冲突
System.ComponentModel.DataAnnotations.Schema 冲突 Entity Framework 与 .net4.5 的 System.ComponentModel.D ...
- System.ComponentModel.DataAnnotations 命名空间和RequiredAttribute 类
System.ComponentModel.DataAnnotations 命名空间提供定义 ASP.NET MVC 和 ASP.NET 数据控件的类的特性. RequiredAttribute 指定 ...
- 解决EntityFramework与System.ComponentModel.DataAnnotations命名冲突
比如,定义entity时指定一个外键, [ForeignKey("CustomerID")] public Customer Customer { get; set; } 编译时报 ...
- 使用System.ComponentModel.DataAnnotations验证字段数据正确性
在.NET MVC 中,当页面提交model到Action的时候,自动填充ModelState.使用ModelState.IsValid进行方便快捷的数据验证,其验证也是调用命名空间System.Co ...
- C# 特性 System.ComponentModel 命名空间属性方法大全,System.ComponentModel 命名空间的特性
目录: System.ComponentModel 特性命名空间与常用类 System.ComponentModel.DataAnnotations ComponentModel - Classes ...
- “CreateRiaClientFilesTask”任务意外失败。 未能加载文件程序集“System.ComponentModel.DataAnnot...
错误 77 “CreateRiaClientFilesTask”任务意外失败. System.Web.HttpException (0x80004005): 未能加载文件或程序集“System. ...
- 对于System.Net.Http的学习(三)——使用 HttpClient 检索与获取过程数据
对于System.Net.Http的学习(一)——System.Net.Http 简介 对于System.Net.Http的学习(二)——使用 HttpClient 进行连接 如何使用 HttpCli ...
随机推荐
- mvc+webapi 单元测试
1.前言 现在这个项目已经有阶段性的模块完成了,所以就想着对这些模块进行单元测试,以保证项目的代码的质量.首先虽然标题是mvc+webapi实质上我只是对mvc进行的测试.用的时候vs的unit te ...
- Monitoring Processes with Supervisord
If you're interested in more of this type of content, check out the Servers for Hackers eBook! As so ...
- linux学习笔记-前篇
大学毕业已经快三年了,从事嵌入式开发的工作也快三年了. 不过,老干些裸机开发,感觉很是枯燥,一咬牙一跺脚,决定从今天开始学习Linux操作系统,顺便记录下学习过程中所遇到的问题与心得. 自己从前完全没 ...
- zorka源码解读之Instrument实现原理
主要用到三方面技术: beanshell来实现可扩展:告诉zorkaAgent插桩的具体需求,包括插桩的方法和值.插桩的时机.插桩追踪记录方式等. Instrument来通过代理的方式访问JVM,实现 ...
- Spring任务调度之Spring-Task
一.前言 上面两篇介绍了在Spring 中使用Timer与Quartz,本篇将介绍Spring3.0以后自主开发的定时任务工具,spring task,可以将它比作一个轻量级的Quartz,而且使用起 ...
- xml转义字符
解析XML文件时,如果有多个转义学符可以用 <![CDATA[含有转义字符的内容]]
- seajs实现JavaScript 的 模块开发及按模块加载
seajs实现了JavaScript 的 模块开发及按模块加载.用来解决繁琐的js命名冲突,文件依赖等问题,其主要目的是令JavaScript开发模块化并可以轻松愉悦进行加载. 官方文档:http:/ ...
- javascript 学习之自定义滚动条加滚轮事件
要自己写一个自定义滚动条加上滚轮事件,之前的没有滚轮事件不完整,今天整理了一个. 1.滚轮事件是不兼容的,firefox中是必需要用事件绑定的添加,用的DOMMouseScroll,当滚动鼠标的时候, ...
- javascript 时间格式化
添加扩展 //时间格式化扩展Date.prototype.format = function(format){ var o = { "M+" : this.getMonth()+1 ...
- Git系列教程二 基础介绍
一.存储方式 如果让我们设计一个版本控制系统,最简单的方式就是每做一次更改就生成一个新的文件. 这样的方式太占用空间,所以传统的版本控制系统都是保存一个文件的某个版本的全部内容以及其他版本相对于这个版 ...