Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#枚举包含值_C#_Enums_Contains - Fatal编程技术网

C#枚举包含值

C#枚举包含值,c#,enums,contains,C#,Enums,Contains,我有一个枚举 enum myEnum2 { ab, st, top, under, below} 我想写一个函数来测试myEnum中是否包含给定的值 诸如此类: private bool EnumContainValue(Enum myEnum, string myValue) { return Enum.GetValues(typeof(myEnum)) .ToString().ToUpper().Contains(myValue.ToUpper()

我有一个枚举

enum myEnum2 { ab, st, top, under, below}
我想写一个函数来测试myEnum中是否包含给定的值

诸如此类:

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

但它不起作用,因为无法识别myEnum参数。

请使用正确的枚举名称(
myEnum2


此外,如果您正在针对字符串值进行测试,您可能希望使用
GetNames
而不是
GetValues

无需编写自己的:

    // 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
}
为什么不使用

Enum.IsDefined(typeof(myEnum), value);
顺便说一句,创建泛型
Enum
类很好,它围绕着对
Enum
的调用(实际上我想知道为什么类似的东西没有添加到Framework2.0或更高版本中):

就用这个方法

-返回指定枚举中是否存在具有指定值的常量的指示

范例

enum myEnum2 { ab, st, top, under, below};
myEnum2 value = myEnum2.ab;
 Console.WriteLine("{0:D} Exists: {1}", 
                        value, myEnum2.IsDefined(typeof(myEnum2), value));
只需将枚举强制转换为:

string something = (string)myEnum;

现在比较很容易,就像你喜欢的那样

我认为你在使用ToString()时出错了

尝试进行Linq查询

private bool EnumContainValue(Enum myEnum, string myValue)
{
    var query = from enumVal in Enum.GetNames(typeof(GM)).ToList()
                       where enumVal == myValue
                       select enumVal;

    return query.Count() == 1;
}
也可以使用此选项:

    enum myEnum2 { ab, st, top, under, below }
    static void Main(string[] args)
    {
        myEnum2 r;
        string name = "ab";
        bool result = Enum.TryParse(name, out r);
    }
结果将包含值是否包含在enum中。

public static T ConvertToEnum(此字符串值)
   public static T ConvertToEnum<T>(this string value)
    {
        if (typeof(T).BaseType != typeof(Enum))
        {
            throw new InvalidCastException("The specified object is not an enum.");
        }
        if (Enum.IsDefined(typeof(T), value.ToUpper()) == false)
        {
            throw new InvalidCastException("The parameter value doesn't exist in the specified enum.");
        }
        return (T)Enum.Parse(typeof(T), value.ToUpper());
    }
{ if(typeof(T).BaseType!=typeof(Enum)) { 抛出新的InvalidCastException(“指定的对象不是枚举”); } if(Enum.IsDefined(typeof(T),value.ToUpper())==false) { 抛出新的InvalidCastException(“参数值在指定的枚举中不存在”); } return(T)Enum.Parse(typeof(T),value.ToUpper()); }
在本例中,您使用ToString()所做的是:

Enum.GetValues(typeof(myEnum)).ToString()…
相反,您应该编写:

Enum.GetValues(typeof(myEnum).ToString()...
不同之处在于括号中…

如果您的问题类似于“我有一个枚举类型,
enum MyEnum{onenummember,othernummember}
,并且我希望有一个函数告诉您此枚举类型是否包含具有特定名称的成员,那么您要查找的是
System.enum.IsDefined
方法:

Enum.IsDefined(typeof(MyEnum), MyEnum.OneEnumMember); //returns true
Enum.IsDefined(typeof(MyEnum), "OtherEnumMember"); //returns true
Enum.IsDefined(typeof(MyEnum), "SomethingDifferent"); //returns false
如果您的问题是“我有一个枚举类型的实例,它具有
标志
属性,并且我想有一个函数来告诉此实例是否包含特定的枚举值,那么该函数如下所示:

public static bool ContainsValue<TEnum>(this TEnum e, TEnum val) where Enum: struct, IComparable, IFormattable, IConvertible
{
    if (!e.GetType().IsEnum)
        throw new ArgumentException("The type TEnum must be an enum type.", nameof(TEnum));

    dynamic val1 = e, val2 = val;
    return (val1 | val2) == val1;
}
publicstaticbool包含value(这个TEnum e,TEnum val),其中Enum:struct,IComparable,IFormattable,IConvertible
{
如果(!e.GetType().IsEnum)
抛出新ArgumentException(“类型TEnum必须是枚举类型。”,nameof(TEnum));
动态val1=e,val2=val;
返回值(val1 | val2)=val1;
}

希望我能帮上忙。

别忘了标记已接受的答案。你能详细说明一下为什么下面的答案都不能解决你的问题吗?也许社区可以提供一个这样做的方法,你可以成为一个好的用户,并将其标记为好的。请在你建议的答案中突出显示缺少的第二个括号(在myEnum之后)。为什么不将方法改为泛型而不是类?不错的小扩展方法会很棒。@nawfal非泛型
Enum
类在C#中已经存在。同样对我来说,
Enum.GetValues()
Enum.GetValues()
可读性稍微好一点,我同意
Enum.GetValues()
可读性更高,但是
Enum.GetValues()
是框架中最常见的东西&因此后者感觉像在家里一样。比如
Enum.TryParse
Tuple.Create
。可能是因为在静态类
Enum
上,
T
的有效性只适用于您正在调用的静态方法,因此必须对该方法进行更合理的约束,不是类。当作用域仅限于(后续的、静态的)方法调用时,类级别上的约束也会觉得有点多余。使用
Enum.GetValues()
目的非常明确。我个人更喜欢
Enum.GetValues()
,只是在框架中几乎看不到它。@lazyberezovsky你能在
T上添加
约束吗?那太好了。
Enum.IsDefined(typeof(MyEnum), MyEnum.OneEnumMember); //returns true
Enum.IsDefined(typeof(MyEnum), "OtherEnumMember"); //returns true
Enum.IsDefined(typeof(MyEnum), "SomethingDifferent"); //returns false
public static bool ContainsValue<TEnum>(this TEnum e, TEnum val) where Enum: struct, IComparable, IFormattable, IConvertible
{
    if (!e.GetType().IsEnum)
        throw new ArgumentException("The type TEnum must be an enum type.", nameof(TEnum));

    dynamic val1 = e, val2 = val;
    return (val1 | val2) == val1;
}