C#枚举包含值 [英] C# enum contains value

查看:178
本文介绍了C#枚举包含值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举

enum myEnum2 { ab, st, top, under, below}

我想编写一个函数来测试一个给定的值是否包含在myEnum中

I would like to write a function to test if a given value is included in myEnum

这样的东西:

private bool EnumContainValue(Enum myEnum, string myValue)
{
     return Enum.GetValues(typeof(myEnum))
                .ToString().ToUpper().Contains(myValue.ToUpper()); 
}

但由于myEnum参数无法识别,它不起作用。 >

But it doesn't work because myEnum parameter is not recognized.

推荐答案

不需要自己写:

    // Summary:
    //     Returns an indication whether a constant with a specified value exists in
    //     a specified enumeration.
    //
    // Parameters:
    //   enumType:
    //     An enumeration type.
    //
    //   value:
    //     The value or name of a constant in enumType.
    //
    // Returns:
    //     true if a constant in enumType has a value equal to value; otherwise, false.

    public static bool IsDefined(Type enumType, object value);

示例:

if (System.Enum.IsDefined(MyEnumType, MyValue))
{
    // Do something
}

这篇关于C#枚举包含值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆