我有枚举:
[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
属性是否包含当前日期?
答案 0 :(得分:9)
Enum有方法HasFlag
来确定当前实例中是否设置了一个或多个位字段。
答案 1 :(得分:6)
使用按位运算符&
查看某个值是否属于集合的一部分:
var today = WeekDays.Thursday;
var workdays = WeekDays.WorkDays;
if((today & workdays) == today) {
// today is a workday
}
if((today & WeekDays.Friday) == today) {
// it's friday
}
答案 2 :(得分:3)
使用&
:
[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();
}
答案 3 :(得分:3)
WeekDays weekDayValue = .... ;
var today = Enum.Parse(typeof(WeekDays),DateTime.Now.DayOfWeek.ToString())
bool matches = ( weekDayValue & today ) == today;
答案 4 :(得分:1)
做的:
int r = (int)(WeekDays.WorkDays & WeekDays.Sunday)
if (r !=0)
you have it.
答案 5 :(得分:1)
您只需要使用按位布尔逻辑来执行此操作。如果你要说
WeekDays.Tuesday & WeekDays.WorkDays
然后布尔逻辑将返回4(因为4& 62 = 4)。
基本上是&对于每个位位置,如果两者都是1,则返回该数字。所以你只需要检查它是否是> 0
要以当前格式获取今天,那么你需要做一些数学......
(int)DateTime.Now.DayOfWeek
将返回一周中的某一天
0(星期日)至6日(星期六)。
我们需要映射这些以匹配您的范围。幸运的是,这很容易用Math.Pow。
int today = Math.Pow(2,(int)DateTime.Now.DayOfWeek);
if (today&WeekDays.WorkDays>0)
isWorkDay = true;
else
isWorkDay = false;
答案 6 :(得分:0)
获取所有枚举名称和值,然后执行'和'计算以测试WeekDays是否包含当天