使用Enum.IsDefined()方法。官方文档

下面是测试例子:
枚举类
public enum Roles
{
管理员, 高级用户, 普通用户
}
主函数
static void Main(string[] args)
{
while (true)
{
string role = Console.ReadLine();
bool flag = Enum.IsDefined(typeof(Roles), role);
Console.WriteLine(flag);
}
}
结果:

本文介绍如何使用C#中的Enum.IsDefined()方法来检查一个字符串是否为枚举类型的有效成员。通过一个简单的示例,演示了如何在控制台应用程序中实现这一功能。
791





