StringLengthAttribute.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace GatewayTool.Models
  7. {
  8. public abstract class AbstractValidateAttribute : Attribute
  9. {
  10. //和接口类似,抽象方法只声明方法
  11. public abstract bool Validate(object objValue);
  12. }
  13. [AttributeUsage(AttributeTargets.Property)]
  14. public class StringLengthAttribute : AbstractValidateAttribute
  15. {
  16. //字段
  17. private int _Mni = 0;
  18. private int _Max = 0;
  19. public StringLengthAttribute(int min, int max)
  20. {
  21. this._Max = max;
  22. this._Mni = min;
  23. }
  24. public override bool Validate(object objValue)
  25. {
  26. return objValue != null
  27. && objValue.ToString().Length >= this._Mni
  28. && objValue.ToString().Length <= this._Max;
  29. }
  30. }
  31. public static class AttributeExtend
  32. {
  33. public static bool Validate<T>(this T t)
  34. {
  35. Type type = t.GetType();
  36. foreach (var property in type.GetProperties())//属性上查找
  37. {
  38. if (property.IsDefined(typeof(AbstractValidateAttribute), true))
  39. {
  40. object objValue = property.GetValue(t);
  41. foreach (AbstractValidateAttribute attribute in property.GetCustomAttributes(typeof(AbstractValidateAttribute), true))
  42. {
  43. if (!attribute.Validate(objValue))//如果成功了以后 就继续验证,否则就直接返回
  44. {
  45. return false;
  46. }
  47. }
  48. }
  49. }
  50. return true;
  51. }
  52. }
  53. }