我有一个枚举:
[Flags]
public enum WeekDays
{
Monday = 1,
Tuesday = 2,
Wednesday = 4,
Thursday = 8,
Friday = 16,
Saturday = 32,
Sunday = 64
}
如果我这样做:
var weekDays = WeekDays.Monday | WeekDays.Tuesday | WeekDays.Friday;
如何检查周日是否设置了Monday
的字符串?
答案 0 :(得分:3)
查看以下代码。您可以使用HasFlag
属性:
class Program
{
[Flags]
public enum WeekDays
{
Monday = 1,
Tuesday = 2,
Wednesday = 4,
Thursday = 8,
Friday = 16,
Saturday = 32,
Sunday = 64
}
private static string result;
static void Main()
{
var wd = new WeekDays();
Console.WriteLine(wd.HasFlag(WeekDays.Monday));
wd = WeekDays.Monday;
Console.WriteLine(wd.HasFlag(WeekDays.Monday));
bool is_defined = Enum.IsDefined(typeof(WeekDays), "Monday");
Console.WriteLine(is_defined);
bool is_not_defined = Enum.IsDefined(typeof(WeekDays), "Mondays");
Console.WriteLine(is_not_defined);
bool has_flag_by_string = Enum.TryParse<WeekDays>("Monday", out wd);
Console.WriteLine(has_flag_by_string);
Console.ReadLine();
}
}
修改的
添加了按字符串检查属性是否存在的功能。
编辑2
添加了Enum.TryParse<>
来解析字符串值。
参考:
https://msdn.microsoft.com/en-us/library/system.enum.hasflag(v=vs.110).aspx
答案 1 :(得分:2)
我想你想要这个
WeekDays days = WeekDays.Monday | WeekDays.Tuesday;
string monday = "Monday";
WeekDays day;
if (Enum.TryParse(monday, true, out day))
{
if (days.HasFlag(day))
{
Console.WriteLine("Has {0}", monday);
}
else
{
Console.WriteLine("Does not have {0}", monday);
}
}
else
{
Console.WriteLine("invalid string");
}
首先,您可以使用Enum.TryParse
将字符串解析为枚举值,或者确定字符串是否无效。然后使用HasFlag
查看是否包含它。