C#中自定义特性验证实体类数据
作者:互联网
一、抽象基类BaseAttribute
/// <summary>
/// BaseAttribute 的摘要说明
/// </summary>
public abstract class BaseAttribute : Attribute
{
public abstract string Validate(object value);
}
二、自定义特性类
定义两个特性,RangeAttribute和MailAttribute,分别用来验证数字范围和邮箱正则匹配
- RangeAttribute
/// <summary>
/// 数值验证
/// </summary>
public class RangeAttribute : BaseAttribute
{
private readonly int _min, _max;
public RangeAttribute(int min, int max)
{
_min = min;
_max = max;
}
public override string Validate(object value)
{
try
{
int _value = Convert.ToInt32(value);
if (_value < _min || _value > _max)
{
return string.Format("验证失败:数值应处于{0}和{1}之间", _min, _max);
}
}
catch (Exception ex)
{
return "验证异常:" + ex.Message;
}
return "";
}
}
- MailAttribute
/// <summary>
/// 邮箱验证
/// </summary>
public class MailAttribute : BaseAttribute
{
public override string Validate(object value)
{
try
{
string _value = Convert.ToString(value);
if (!Regex.IsMatch(_value, "^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"))
{
return "验证失败:请输入正确的邮箱地址";
}
}
catch (Exception ex)
{
return "验证异常:" + ex.Message;
}
return "";
}
}
三、定义实体学生类
学生实体类的字段上使用自定义特性
/// <summary>
/// Student 的摘要说明
/// </summary>
public class Student
{
public string Name { get; set; }
[Range(18, 28)]
public int Age { get; set; }
[Mail]
public string mail { get; set; }
}
四、静态拓展方法
通过反射找到学生实体的标注自定义特性,依次进行对实体字段进行验证
/// <summary>
/// 扩展类
/// </summary>
public static class ValidateEx
{
/// <summary>
/// 实体扩展方法
/// 验证方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="model"></param>
/// <returns></returns>
public static string Validate<T>(this T model) where T : class
{
string msg = null;
//获取类型
Type type = model.GetType();
//反射找到属性值
var properties = type.GetProperties();
foreach (var prop in properties)
{
//是否将指定类型或其派生类型的一个或多个特性应用于此成员
if (prop.IsDefined(typeof(BaseAttribute), true))
{
var attributes = prop.GetCustomAttributes(typeof(BaseAttribute), true);//获取自定义的特性
foreach (BaseAttribute attr in attributes)
{
msg += attr.Validate(prop.GetValue(model)) + "\r\n";
}
}
}
return msg;
}
}
五、测试验证方法
/// <summary>
/// 按钮测试方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
Student model = new Student
{
Name = txt_name.Text,
Age = int.Parse(txt_age.Text),
mail = txt_mail.Text
};
string msg = model.Validate();
if (!string.IsNullOrWhiteSpace(msg))
{
MessageBox.Show(msg);
}
else
{
MessageBox.Show("验证通过");
}
}
标签:实体类,return,string,自定义,验证,C#,value,BaseAttribute,public 来源: https://www.cnblogs.com/wml-it/p/16578204.html