我有这样一个枚举:

 public enum PromotionTypes
{
    Unspecified = 0, 
    InternalEvent = 1,
    ExternalEvent = 2,
    GeneralMailing = 3,  
    VisitBased = 4,
    PlayerIntroduction = 5,
    Hospitality = 6
}

我想判断一下这个枚举是否包含我给出的数字.例如:当我给出4时,Enum包含它,所以我想返回True,如果我给7,那么这个Enum中没有7,所以它返回False. 我try 了Enum.IsDefine,但它只判断字符串值. 我怎么才能做到这一点呢?

推荐答案

IsDefined法需要two parameters.first parameter is the type of the enumeration to be checked.这种类型通常是通过使用typeof表达式获得的.second parameter is defined as a basic object.它用于指定整数值或包含要查找的常量名称的字符串.返回值是一个布尔值,如果该值存在则为true,如果不存在则为false.

enum Status
{
    OK = 0,
    Warning = 64,
    Error = 256
}

static void Main(string[] args)
{
    bool exists;

    // Testing for Integer Values
    exists = Enum.IsDefined(typeof(Status), 0);     // exists = true
    exists = Enum.IsDefined(typeof(Status), 1);     // exists = false

    // Testing for Constant Names
    exists = Enum.IsDefined(typeof(Status), "OK");      // exists = true
    exists = Enum.IsDefined(typeof(Status), "NotOK");   // exists = false
}

100

.net相关问答推荐

无法在Designer、VS2022、. NET 8中打开WinForms表单'

ZstdNet库的问题:Src大小不正确,异常

NETSDK1083:无法识别指定的 RuntimeIdentifierwin10-x64

从 Contentful 中的富文本元素中获取价值?

.NET 4.5 项目未在 Visual Studio 2022 中编译

即时窗口中的动态导致Microsoft.CSharp.RuntimeBinder.Binder未定义或导入错误

xunit Assert.ThrowsAsync() 不能正常工作?

调整小数精度,.net

将屏幕捕获为位图

注册 COM 互操作与使程序集 COM 可见

创建多个线程并等待所有线程完成

寻找 .NET 的命令行参数解析器

在 C#/.NET 中组合路径和文件名的最佳方法是什么?

场与财产.性能优化

在 .NET 中获取默认打印机的最佳方法是什么

EF Core 添加迁移构建失败

如何在安装后立即启动 .NET Windows 服务?

如何将 MailMessage 对象作为 *.eml 或 *.msg 文件保存到磁盘

如何重新启动 WPF 应用程序?

嵌套捕获组如何在正则表达式中编号?