123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace XdCxRhDW.Dto.Attribute
- {
- /// <summary>
- /// 2的N次方限制
- /// </summary>
- public class Pow2Attribute : ValidationAttribute
- {
- /// <summary>
- /// 是否包含零,默认不包含
- /// </summary>
- public bool IncludeZero { get; set; } = false;
- /// <summary>
- ///
- /// </summary>
- public Pow2Attribute()
- {
- }
- /// <summary>
- /// 2的N次方验证
- /// </summary>
- /// <param name="value"></param>
- /// <returns></returns>
- /// <exception cref="Exception"></exception>
- public override bool IsValid(object value)
- {
- ErrorMessage = "字段 {0} 必须是2的N次方";
- if (IncludeZero)
- {
- ErrorMessage += "或者0";
- }
- if (value.GetType() == typeof(double))
- {
- double val = (double)value;
- int ivalue = (int)val;
- return IsPow2(ivalue);
- }
- else if (value.GetType() == typeof(int))
- {
- int val = (int)value;
- return IsPow2(val);
- }
- else
- {
- throw new Exception($"{nameof(Pow2Attribute)}只能用于int或double类型!");
- }
- }
- private bool IsPow2(int val)
- {
- var res = val & (val - 1);
- return res == 0;
- }
- }
- }
|