我有一个枚举:
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
查看 System.Enum.Parse:
enum Colors {Red, Green, Blue} // your code: Colors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");