我有一个枚举:
public enum MyColours
{
Red,
Green,
Blue,
Yellow,
Fuchsia,
Aqua,
Orange
}
我有一个字符串:
string colour = "Red";
我希望能够回归:
MyColours.Red
从:
public MyColours GetColour(string colour)
到目前为止,我有:
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?
}
正如你所看到的,我有点卡住了。无论如何都要按值选择枚举器。类似的东西:
MyColour(2)
会导致
MyColour.Green
答案 0 :(得分:344)
查看System.Enum.Parse:
enum Colors {Red, Green, Blue}
// your code:
Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");
答案 1 :(得分:18)
您可以将int强制转换为枚举
(MyColour)2
还有Enum.Parse选项
(MyColour)Enum.Parse(typeof(MyColour), "Red")
答案 2 :(得分:9)
考虑到.NET(+核心)和C#7的最新最大改进,这是最佳解决方案:
var ignoreCase = true;
Enum.TryParse("red", ignoreCase , out MyColours colour);
colour变量可以在Enum.TryParse的范围内使用
答案 3 :(得分:5)
您需要的只是Enum.Parse。
答案 4 :(得分:2)
我标记了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;
}
答案 5 :(得分:1)
您可以使用Enum.Parse
从名称中获取枚举值。您可以使用Enum.GetNames
迭代所有值,并且可以将int转换为枚举以从int值获取枚举值。
像这样,例如:
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
}
或:
public MyColours GetColours(string colour)
{
return (MyColours)Enum.Parse(typeof(MyColours), colour, true); // true = ignoreCase
}
如果未找到值,后者将抛出ArgumentException,您可能希望在函数内捕获它并返回默认值。
答案 6 :(得分:0)
如前面的答案中所述,您可以直接转换为基础数据类型(int - &gt;枚举类型)或解析(string - &gt;枚举类型)。
但要注意 - 枚举没有.TryParse,所以你需要在解析周围使用try / catch块来捕获失败。
答案 7 :(得分:0)
您可能还想查看此博文中的一些建议: My new little friend, Enum<T>
这篇文章描述了一种创建一个非常简单的通用助手类的方法,它可以避免Enum.Parse
固有的丑陋的转换语法 - 而不是你在代码中写这样的东西:
MyColours colour = Enum<MyColours>.Parse(stringValue);
或者查看同一篇文章中的一些评论,其中讨论了使用扩展方法实现类似的方法。
答案 8 :(得分:0)
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);
}
}
}
答案 9 :(得分:0)
可能对您有用的一件事(除了目前为止提供的已经有效/好的答案)是StringEnum提供的想法here
使用此功能,您可以将枚举定义为类(示例位于vb.net中):
&LT; StringEnumRegisteredOnly(),DebuggerStepThrough(), ImmutableObject(真)&GT;公共不可继承的类 eAuthenticationMethod继承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")
结束班
现在你可以像使用enum一样使用这个类:eAuthenticationMethod.WindowsAuthentication,这就像分配' W ' WindowsAuthentication (在枚举内)如果要从属性窗口(或使用System.ComponentModel.Description属性的其他内容)查看此值,您将获得“使用Windows身份验证”。
我已经使用了很长时间了,它使代码更加清晰。
答案 10 :(得分:0)
(MyColours)Enum.Parse(typeof(MyColours), "red", true); // MyColours.Red
(int)((MyColours)Enum.Parse(typeof(MyColours), "red", true)); // 0
答案 11 :(得分:0)
试试这个方法。
public static class Helper
{
public static T FromStr<T>(string str) where T : struct, System.Enum
=> System.Enum.TryParse<T>(value:str,ignoreCase:true,result:out var result)
? result
: default;
public static T? FromStrNull<T>(string str) where T : struct, System.Enum
=> System.Enum.TryParse<T>(value: str,ignoreCase: true,result: out var result)
? result
: null;
}
然后像这样使用
var color = Helper.FromStr<MyColours>("red");
答案 12 :(得分:-1)
var color = Enum.Parse<Colors>("Green");