123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace GatewayTool.Models
- {
- public abstract class AbstractValidateAttribute : Attribute
- {
- //和接口类似,抽象方法只声明方法
- public abstract bool Validate(object objValue);
- }
- [AttributeUsage(AttributeTargets.Property)]
- public class StringLengthAttribute : AbstractValidateAttribute
- {
- //字段
- private int _Mni = 0;
- private int _Max = 0;
- public StringLengthAttribute(int min, int max)
- {
- this._Max = max;
- this._Mni = min;
- }
- public override bool Validate(object objValue)
- {
- return objValue != null
- && objValue.ToString().Length >= this._Mni
- && objValue.ToString().Length <= this._Max;
- }
- }
- public static class AttributeExtend
- {
- public static bool Validate<T>(this T t)
- {
- Type type = t.GetType();
- foreach (var property in type.GetProperties())//属性上查找
- {
- if (property.IsDefined(typeof(AbstractValidateAttribute), true))
- {
- object objValue = property.GetValue(t);
- foreach (AbstractValidateAttribute attribute in property.GetCustomAttributes(typeof(AbstractValidateAttribute), true))
- {
- if (!attribute.Validate(objValue))//如果成功了以后 就继续验证,否则就直接返回
- {
- return false;
- }
- }
- }
- }
- return true;
- }
- }
- }
|