简体   繁体   中英

C#: Getting an enum value by string?

I'm trying to get a enum value from a string in a database, below is the enum I am trying to get the value from, the DB value is a string.

internal enum FieldType
{
    Star,
    Ghost,
    Monster,
    Trial,
    None
}

Heres the DB part:

using (var reader = dbConnection.ExecuteReader())
{
    var field = new Field(
        reader.GetString("field_type"),
        reader.GetString("data"),
        reader.GetString("message")
    );
}

Now, I had this method that did it for me, but it seems overkill to have a method do something that C# could already do, can anyone tell me if theres a way I can do this within the C# language without creating my own method?

public static FieldType GetType(string Type)
{
    switch (Type.ToLower())
    {
        case "star":
            return FieldType.Star;

        case "ghost":
            return FieldType.Ghost;

        case "monster":
            return FieldType.Monster;

        case "trial":
            return FieldType.Trial;

        default:
        case "none":
            return FieldType.None;
    }
}

In essence, I believe what you need is parsing from string to an enum. This would work if the value of the string is matching the enum value (in which it seems it is here).

Enum.TryParse(Type, out FieldType myFieldType);


Enum.TryParse(Type, ignoreCase, out FieldType myFieldType);

First method case-sensitive while the second allows you to specify case sensitivity.

How should I convert a string to an enum in C#?

Let's define a test string first:

String text = "Star";

Before .NET 4.0 ( MSDN reference ):

// Case Sensitive
FieldType ft = (FieldType)Enum.Parse(typeof(FieldType), text, false);

// Case Insensitive
FieldType ft = (FieldType)Enum.Parse(typeof(FieldType), text, true);

but with Enum.Parse you have to manage a potential exception being thrown if the parsing process fails:

FieldType ft;

try
{
    ft = (FieldType)Enum.Parse(typeof(FieldType), text, true);
}
catch (Exception e)
{
    ft = FieldType.None;
}

Since .NET 4.0 ( MSDN reference ):

FieldType ft;

// Case Sensitive
if (!Enum.TryParse(text, false, out ft))
    ft = FieldType.None;

// Case Insensitive
if (!Enum.TryParse(text, true, out ft))
    ft = FieldType.None;

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