using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XdCxRhDW.Dto.Attribute
{
///
/// 2的N次方限制
///
public class Pow2Attribute : ValidationAttribute
{
///
/// 是否包含零,默认不包含
///
public bool IncludeZero { get; set; } = false;
///
///
///
public Pow2Attribute()
{
}
///
/// 2的N次方验证
///
///
///
///
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;
}
}
}