在 Enum 中搜索字符串并返回 Enum

2024-02-29

我有一个枚举:

public enum MyColours
{
    Red,
    Green,
    Blue,
    Yellow,
    Fuchsia,
    Aqua,
    Orange
}

我有一个字符串:

string colour = "Red";

我希望能够返回:

MyColours.Red

from:

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");

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Enum 中搜索字符串并返回 Enum 的相关文章

随机推荐