简体   繁体   中英

C# enums type conversion

I have got a variable in Appsettings namely,

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

I have to convert the variable _tablename to a specific enum type. I understand that we cannot use constructors in C# enums.

Any help would be appreciated.

Have a look here:

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

You need to parse. For example, if you have an enum Color :

enum Color
{
    Red,
    Yellow,
    Green
}

You could use TryParse like this:

Color myColor;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM