C# 枚举包含值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13248869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# enum contains value
提问by Fred Smith
I have an enum
我有一个枚举
enum myEnum2 { ab, st, top, under, below}
I would like to write a function to test if a given value is included in myEnum
我想编写一个函数来测试给定的值是否包含在 myEnum 中
something like that:
类似的东西:
private bool EnumContainValue(Enum myEnum, string myValue)
{
return Enum.GetValues(typeof(myEnum))
.ToString().ToUpper().Contains(myValue.ToUpper());
}
But it doesn't work because myEnum parameter is not recognized.
但它不起作用,因为无法识别 myEnum 参数。
采纳答案by LightStriker
No need to write your own:
无需自己编写:
// 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);
Example:
例子:
if (System.Enum.IsDefined(MyEnumType, MyValue))
{
// Do something
}
回答by Cristian Lupascu
Use the correct name of the enum (myEnum2).
使用枚举的正确名称 ( myEnum2)。
Also, if you're testing against a string value you may want to use GetNamesinstead of GetValues.
此外,如果你对一个字符串值,测试你可能要使用GetNames替代GetValues。
回答by Sergey Berezovskiy
Why not use
为什么不使用
Enum.IsDefined(typeof(myEnum), value);
BTWit's nice to create generic Enum<T>class, which wraps around calls to Enum(actually I wonder why something like this was not added to Framework 2.0 or later):
顺便说一句,创建泛型Enum<T>类很好,它环绕调用Enum(实际上我想知道为什么这样的东西没有添加到 Framework 2.0 或更高版本):
public static class Enum<T>
{
public static bool IsDefined(string name)
{
return Enum.IsDefined(typeof(T), name);
}
public static bool IsDefined(T value)
{
return Enum.IsDefined(typeof(T), value);
}
public static IEnumerable<T> GetValues()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
// etc
}
This allows to avoid all this typeofstuff and use strongly-typed values:
这允许避免所有这些typeof东西并使用强类型值:
Enum<StringSplitOptions>.IsDefined("None")
回答by Pranay Rana
just use this method
只需使用此方法
Enum.IsDefined Method- Returns an indication whether a constant with a specified value exists in a specified enumeration
Enum.IsDefined 方法- 返回指定枚举中是否存在具有指定值的常量的指示
Example
例子
enum myEnum2 { ab, st, top, under, below};
myEnum2 value = myEnum2.ab;
Console.WriteLine("{0:D} Exists: {1}",
value, myEnum2.IsDefined(typeof(myEnum2), value));
回答by Talha
just cast the enum as:
只需将枚举转换为:
string something = (string)myEnum;
and now comparison is easy as you like
现在比较很容易,随心所欲
回答by MaLKaV_eS
I think that you go wrong when using ToString().
我认为您在使用 ToString() 时出错了。
Try making a Linq query
尝试进行 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;
}
回答by Akash Mehta
Also can use this:
也可以使用这个:
enum myEnum2 { ab, st, top, under, below }
static void Main(string[] args)
{
myEnum2 r;
string name = "ab";
bool result = Enum.TryParse(name, out r);
}
The result will contain whether the value is contained in enum or not.
结果将包含该值是否包含在枚举中。
回答by c-sharp
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());
}
回答by c-sharp
What you're doing with ToString() in this case is to:
在这种情况下,您对 ToString() 所做的是:
Enum.GetValues(typeof(myEnum)).ToString()...instead you should write:
Enum.GetValues(typeof(myEnum)).ToString()...相反,你应该写:
Enum.GetValues(typeof(myEnum).ToString()...
The difference is in the parentheses...
区别在于括号...
回答by florien
If your question is like "I have an enum type, enum MyEnum { OneEnumMember, OtherEnumMember }, and I'd like to have a function which tells whether this enum type contains a member with a specific name, then what you're looking for is the System.Enum.IsDefinedmethod:
如果您的问题类似于“我有一个枚举类型,enum MyEnum { OneEnumMember, OtherEnumMember }并且我想要一个函数来判断该枚举类型是否包含具有特定名称的成员,那么您正在寻找的是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
If your question is like "I have an instance of an enum type, which has Flagsattribute, and I'd like to have a function which tells whether this instance contains a specific enum value, then the function looks something like this:
如果您的问题是“我有一个枚举类型的实例,它具有Flags属性,并且我想要一个函数来告诉这个实例是否包含特定的枚举值,那么该函数看起来像这样:
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;
}
Hope I could help.
希望我能帮上忙。

