gpt4 book ai didi

c# 枚举标志检查字符串是否在标志中

转载 作者:太空宇宙 更新时间:2023-11-03 19:57:14 24 4
gpt4 key购买 nike

我有一个枚举:

[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;

如何检查是否在 weekDays 中设置了字符串,例如 Monday

最佳答案

检查以下代码。您可以使用 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

关于c# 枚举标志检查字符串是否在标志中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32259107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com