I have the enum:
[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
}
And, I have property WeekDays
in a class that contain value of WeekDays
enum:
public int WeekDays {get; set;}
For example WorkDays
contain 62( from Monday to Friday).
How to check that current WeekDays
property contain current day?
Enum具有方法HasFlag
用于确定是否在当前实例中设置了一个或多个位字段。
Use the bitwise operator &
to see if a value is part of a set:
var today = WeekDays.Thursday;
var workdays = WeekDays.WorkDays;
if((today & workdays) == today) {
// today is a workday
}
if((today & WeekDays.Friday) == today) {
// it's friday
}
Use &
:
[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.
You just need to use bitwise boolean logic to do this. if you were to say
WeekDays.Tuesday & WeekDays.WorkDays
then the boolean logic would return 4 (since 4&62 = 4).
Essentially the & is saying that for each bit position if both are 1 then return that number. So you then just need to check if it is > 0.
To get Today in your current format then you'll need to do a bit of maths...
(int)DateTime.Now.DayOfWeek
will return the day of the week ranging from 0 (sunday) to 6 (saturday).
We need to map these to match your range. Fortunately this is easy to do with Math.Pow.
int today = Math.Pow(2,(int)DateTime.Now.DayOfWeek);
if (today&WeekDays.WorkDays>0)
isWorkDay = true;
else
isWorkDay = false;
获取所有枚举名称和值,然后执行“和”计算以测试WeekDays是否包含当天
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.