搜索在枚举一个字符串,返回枚举 [英] Search for a string in Enum and return the Enum
本文介绍了搜索在枚举一个字符串,返回枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个枚举:
公开枚举MyColours
{
红,
绿色,
蓝色,
黄色,
紫红色,
水族,
橙子
}
和我有一个字符串:
串色=红;
我希望能够返回:
MyColours.Red
从:
公共MyColours GetColour(串色)
到目前为止,我有:
公共MyColours GetColours(串色)
{
字符串[] =颜色Enum.GetNames(typeof运算(MyColours));
INT [] =值Enum.GetValues(typeof运算(MyColours));
INT I;
的for(int i = 0; I< colours.Length;我++)
{
如果(colour.Equals(颜色[I],StringComparison.Ordinal)
打破;
}
int值=值[I]
//我都知道匹配的枚举的信息
//但我怎么转换这一信息纳入返回
// MyColour枚举?
}
正如你所看到的,我有点卡住了。反正是有选择并通过枚举值。是这样的:
MyColour(2)
将导致
MyColour.Green
解决方案
检查System.Enum.Parse:
枚举颜色{红,绿,蓝}//你的code:
色色=(色彩)System.Enum.Parse(typeof运算(颜色),绿色);
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 and enumerator by value. Something like:
MyColour(2)
would result in
MyColour.Green
解决方案
check out System.Enum.Parse:
enum Colors {Red, Green, Blue}
// your code:
Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");
这篇关于搜索在枚举一个字符串,返回枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文