Pow2Attribute.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace XdCxRhDW.Dto.Attribute
  8. {
  9. /// <summary>
  10. /// 2的N次方限制
  11. /// </summary>
  12. public class Pow2Attribute : ValidationAttribute
  13. {
  14. /// <summary>
  15. /// 是否包含零,默认不包含
  16. /// </summary>
  17. public bool IncludeZero { get; set; } = false;
  18. /// <summary>
  19. ///
  20. /// </summary>
  21. public Pow2Attribute()
  22. {
  23. }
  24. /// <summary>
  25. /// 2的N次方验证
  26. /// </summary>
  27. /// <param name="value"></param>
  28. /// <returns></returns>
  29. /// <exception cref="Exception"></exception>
  30. public override bool IsValid(object value)
  31. {
  32. ErrorMessage = "字段 {0} 必须是2的N次方";
  33. if (IncludeZero)
  34. {
  35. ErrorMessage += "或者0";
  36. }
  37. if (value.GetType() == typeof(double))
  38. {
  39. double val = (double)value;
  40. int ivalue = (int)val;
  41. return IsPow2(ivalue);
  42. }
  43. else if (value.GetType() == typeof(int))
  44. {
  45. int val = (int)value;
  46. return IsPow2(val);
  47. }
  48. else
  49. {
  50. throw new Exception($"{nameof(Pow2Attribute)}只能用于int或double类型!");
  51. }
  52. }
  53. private bool IsPow2(int val)
  54. {
  55. var res = val & (val - 1);
  56. return res == 0;
  57. }
  58. }
  59. }