C# 在 Enum 中搜索字符串并返回 Enum
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2290262/
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
Search for a string in Enum and return the Enum
提问by Matt Clarkson
I have an enumeration:
我有一个枚举:
public enum MyColours
{
Red,
Green,
Blue,
Yellow,
Fuchsia,
Aqua,
Orange
}
and I have a string:
我有一个字符串:
string colour = "Red";
I want to be able to return:
我希望能够返回:
MyColours.Red
from:
从:
public MyColours GetColour(string colour)
So far i have:
到目前为止,我有:
public MyColours GetColours(string colour)
{
string[] colours = Enum.GetNames(typeof(MyColours));
int[] values = Enum.GetValues(typeof(MyColours));
int i;
for(int i = 0; i < colours.Length; i++)
{
if(colour.Equals(colours[i], StringComparison.Ordinal)
break;
}
int value = values[i];
// I know all the information about the matched enumeration
// but how do i convert this information into returning a
// MyColour enumeration?
}
As you can see, I'm a bit stuck. Is there anyway to select an enumerator by value. Something like:
正如你所看到的,我有点卡住了。反正有没有按值选择枚举器。就像是:
MyColour(2)
would result in
会导致
MyColour.Green
采纳答案by JMarsch
check out System.Enum.Parse:
查看 System.Enum.Parse:
enum Colors {Red, Green, Blue}
// your code:
Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");
回答by Guvante
You can cast the int to an enum
您可以将 int 转换为枚举
(MyColour)2
There is also the option of Enum.Parse
还有 Enum.Parse 的选项
(MyColour)Enum.Parse(typeof(MyColour), "Red")
回答by OregonGhost
You can use Enum.Parse
to get an enum value from the name. You can iterate over all values with Enum.GetNames
, and you can just cast an int to an enum to get the enum value from the int value.
您可以使用Enum.Parse
从名称中获取枚举值。您可以使用 迭代所有值Enum.GetNames
,并且可以将 int 转换为 enum 以从 int 值中获取 enum 值。
Like this, for example:
像这样,例如:
public MyColours GetColours(string colour)
{
foreach (MyColours mc in Enum.GetNames(typeof(MyColours))) {
if (mc.ToString().Contains(colour)) {
return mc;
}
}
return MyColours.Red; // Default value
}
or:
或者:
public MyColours GetColours(string colour)
{
return (MyColours)Enum.Parse(typeof(MyColours), colour, true); // true = ignoreCase
}
The latter will throw an ArgumentException if the value is not found, you may want to catch it inside the function and return the default value.
如果未找到该值,后者将抛出 ArgumentException,您可能希望在函数内部捕获它并返回默认值。
回答by Bruno Brant
All you need is Enum.Parse.
您只需要Enum.Parse。
回答by Addys
As mentioned in previous answers, you can cast directly to the underlying datatype (int -> enum type) or parse (string -> enum type).
正如前面的答案中提到的,您可以直接转换为基础数据类型(int -> enum 类型)或解析(string -> enum 类型)。
but beware - there is no .TryParse for enums, so you WILL need a try/catch block around the parse to catch failures.
但要注意 - 没有 .TryParse 用于枚举,因此您将需要一个围绕解析的 try/catch 块来捕获失败。
回答by Julian Martin
You might also want to check out some of the suggestions in this blog post: My new little friend, Enum<T>
您可能还想查看这篇博文中的一些建议: 我的新小朋友,Enum<T>
The post describes a way to create a very simple generic helper class which enables you to avoid the ugly casting syntax inherent with Enum.Parse
- instead you end up writing something like this in your code:
这篇文章描述了一种创建一个非常简单的通用辅助类的方法,它使您能够避免固有的丑陋的强制转换语法Enum.Parse
- 相反,您最终会在代码中编写如下内容:
MyColours colour = Enum<MyColours>.Parse(stringValue);
Or check out some of the comments in the same post which talk about using an extension method to achieve similar.
或者查看同一篇文章中的一些评论,这些评论谈论使用扩展方法来实现类似的目标。
回答by Raja
class EnumStringToInt // to search for a string in enum
{
enum Numbers{one,two,hree};
static void Main()
{
Numbers num = Numbers.one; // converting enum to string
string str = num.ToString();
//Console.WriteLine(str);
string str1 = "four";
string[] getnames = (string[])Enum.GetNames(typeof(Numbers));
int[] getnum = (int[])Enum.GetValues(typeof(Numbers));
try
{
for (int i = 0; i <= getnum.Length; i++)
{
if (str1.Equals(getnames[i]))
{
Numbers num1 = (Numbers)Enum.Parse(typeof(Numbers), str1);
Console.WriteLine("string found:{0}", num1);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Value not found!", ex);
}
}
}
回答by Colin
I marked OregonGhost's answer +1, then I tried to use the iteration and realised it wasn't quite right because Enum.GetNames returns strings. You want Enum.GetValues:
我标记了 OregonGhost 的答案 +1,然后我尝试使用迭代并意识到它不太正确,因为 Enum.GetNames 返回字符串。你想要 Enum.GetValues:
public MyColours GetColours(string colour)
{
foreach (MyColours mc in Enum.GetValues(typeof(MyColours)))
if (mc.ToString() == surveySystem)
return mc;
return MyColors.Default;
}
回答by Ando
One thing that might be useful to you (besides the already valid/good answers provided so far) is the StringEnum idea provided here
可能对您有用的一件事(除了迄今为止提供的已经有效/好的答案)是此处提供的 StringEnum 想法
With this you can define your enumerations as classes (the examples are in vb.net):
有了这个,您可以将您的枚举定义为类(示例在 vb.net 中):
< StringEnumRegisteredOnly(), DebuggerStepThrough(), ImmutableObject(True)> Public NotInheritable Class eAuthenticationMethod Inherits StringEnumBase(Of eAuthenticationMethod)
Private Sub New(ByVal StrValue As String) MyBase.New(StrValue) End Sub < Description("Use User Password Authentication")> Public Shared ReadOnly UsernamePassword As New eAuthenticationMethod("UP") < Description("Use Windows Authentication")> Public Shared ReadOnly WindowsAuthentication As New eAuthenticationMethod("W")
End Class
< StringEnumRegisteredOnly(), DebuggerStepThrough(), ImmutableObject(True)> Public NotInheritable Class eAuthenticationMethod Inherits StringEnumBase(Of eAuthenticationMethod)
Private Sub New(ByVal StrValue As String) MyBase.New(StrValue) End Sub < Description("Use User Password Authentication")> Public Shared ReadOnly UsernamePassword As New eAuthenticationMethod("UP") < Description("Use Windows Authentication")> Public Shared ReadOnly WindowsAuthentication As New eAuthenticationMethod("W")
结束类
And now you could use the this class as you would use an enum: eAuthenticationMethod.WindowsAuthentication and this would be essentially like assigning the 'W' the logical value of WindowsAuthentication(inside the enum) and if you were to view this value from a properties window (or something else that uses the System.ComponentModel.Description property) you would get "Use Windows Authentication".
现在你可以像使用枚举一样使用这个类: eAuthenticationMethod.WindowsAuthentication ,这本质上就像为“ W”分配WindowsAuthentication的逻辑值(在枚举内),如果你要从属性中查看这个值窗口(或其他使用 System.ComponentModel.Description 属性的东西)你会得到“使用 Windows 身份验证”。
I've been using this for a long time now and it makes the code more clear in intent.
我已经使用它很长时间了,它使代码的意图更加清晰。
回答by Sandeep Shekhawat
(MyColours)Enum.Parse(typeof(MyColours), "red", true); // MyColours.Red
(int)((MyColours)Enum.Parse(typeof(MyColours), "red", true)); // 0