C#枚举类型转换



我在Appsettings中有一个变量,即

_tablename = ConfigurationManager.AppSettings.Get("Tablename");

我必须将变量_tablename转换为特定的枚举类型。我知道我们不能在C#枚举中使用构造函数。

如有任何帮助,我们将不胜感激。

看看这里:

http://www.dotnetperls.com/enum-parse

using System;
class Program
{
    enum PetType
    {
    None,
    Cat = 1,
    Dog = 2
    }
    static void Main()
    {
    // A.
    // Possible user input:
    string value = "Dog";
    // B.
    // Try to convert the string to an enum:
    PetType pet = (PetType)Enum.Parse(typeof(PetType), value);
    // C.
    // See if the conversion succeeded:
    if (pet == PetType.Dog)
    {
        Console.WriteLine("Equals dog.");
    }
    }
}

您需要解析。例如,如果您有一个枚举Color:

enum Color
{
    Red,
    Yellow,
    Green
}

你可以这样使用TryParse

Color myColor;
if (Enum.TryParse<Color>("Red", out myColor))
{
    // successfully parsed.
}

最新更新