具有flags属性的枚举
本文关键字:枚举 属性 flags 具有 | 更新日期: 2023-09-27 18:25:44
我有一个枚举:
[Flags, Serializable,]
public enum WeekDays {
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
WeekendDays = Sunday | Saturday,
WorkDays = Monday | Tuesday | Wednesday | Thursday | Friday,
EveryDay = WeekendDays | WorkDays
}
并且,我在一个包含WeekDays
枚举值的类中有属性WeekDays
:
public int WeekDays {get; set;}
例如,WorkDays
包含62(从星期一到星期五)
如何检查当前WeekDays
属性是否包含当前日期?
Enum有方法HasFlag
来确定是否在当前实例中设置了一个或多个位字段。
使用逐位运算符&
查看值是否是集合的一部分:
var today = WeekDays.Thursday;
var workdays = WeekDays.WorkDays;
if((today & workdays) == today) {
// today is a workday
}
if((today & WeekDays.Friday) == today) {
// it's friday
}
使用&
:
[Flags, Serializable,]
public enum WeekDays
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
WeekendDays = Sunday | Saturday,
WorkDays = Monday | Tuesday | Wednesday | Thursday | Friday,
EveryDay = WeekendDays | WorkDays
}
public static WeekDays Days { get; set; }
private static void Main(string[] args)
{
WeekDays today = WeekDays.Sunday;
Days = WeekDays.WorkDays;
if ((Days & today) == today)
{
Console.WriteLine("Today is included in Days");
}
Console.ReadKey();
}
WeekDays weekDayValue = .... ;
var today = Enum.Parse(typeof(WeekDays),DateTime.Now.DayOfWeek.ToString())
bool matches = ( weekDayValue & today ) == today;
do:
int r = (int)(WeekDays.WorkDays & WeekDays.Sunday)
if (r !=0)
you have it.
您只需要使用逐位布尔逻辑即可完成此操作。如果你说
WeekDays.Tuesday & WeekDays.WorkDays
则布尔逻辑将返回4(因为4&62=4)。
本质上是&是说对于每个比特位置,如果两者都是1,则返回该数字。因此,您只需要检查它是否大于0。
要想以当前的格式获得《今日》,你需要做一些数学运算。。。
(int)DateTime.Now.DayOfWeek
将返回从0(星期日)至6(星期六)。
我们需要绘制这些地图以匹配您的范围。幸运的是,这对数学很容易做到
int today = Math.Pow(2,(int)DateTime.Now.DayOfWeek);
if (today&WeekDays.WorkDays>0)
isWorkDay = true;
else
isWorkDay = false;
获取所有枚举名称和值,然后执行"answers"计算以测试WeekDays是否包含当前日期