C#枚举类型转换

C# enums type conversion

我在应用程序设置中有一个变量,即

_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.
}