在日常开发中,想必都见过这样的代码 if a=='' ...;if b=='' ...
; 代码冗余且可观赏性非常差;有没有什么方法来解决这个问题呢?可以尝试下使用特性(Attribute
)。
对于特性不了解的话,可以去稍微百度下,也是很简单。.
这里主要做的还是基于实体对象的验证;下面来分析下代码
实现功能:
- 使用特性对数字和邮箱进行验证
开发环境:
开发工具:Visual Studio 2013
.NET Framework版本:4.5
-
创建一个抽象特性类,继承自Attribute,里面只要创建一个验证的抽象方法即可,具体实现让子类取做
public abstract class BaseAttribute : Attribute
{
public abstract string Validate(object value);
}
-
分别创建一个控制数字范围以及邮箱验证的特性类,继承自BaseAttribute,然后实现验证函数
/// <summary>
/// 数值验证
/// </summary>
public class RangeAttribute : BaseAttribute
{
private readonly int _min, _max;
public RangeAttribute(int min, int max)
{
this._min = min;
this._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 "";
}
}
/// <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 "";
}
}
-
创建一个实体类。在字段上加上自定义的特性
public class Model
{
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;
}
}
-
最后写个简单代码看下效果
private void button1_Click(object sender, EventArgs e)
{
Model model = new Model
{
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("验证通过");
}
}
实现效果: