简体   繁体   English

C#:通过字符串获取枚举值?

[英]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. 我正在尝试从数据库中的字符串获取枚举值,以下是我试图从中获取值的枚举,DB值是字符串。

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? 现在,我有了为我做的这种方法,但是让一种方法执行C#已经可以做的事情似乎有些矫kill过正,有人可以告诉我是否有一种方法可以在C#语言中执行此操作而不创建自己的方法吗?

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#? 如何在C#中将字符串转换为枚举?

Let's define a test string first: 首先定义一个测试字符串:

String text = "Star";

Before .NET 4.0 ( MSDN reference ): .NET 4.0之前( MSDN参考 ):

// 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: 但是使用Enum.Parse ,如果解析过程失败,则必须管理可能引发的潜在异常:

FieldType ft;

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

Since .NET 4.0 ( MSDN reference ): .NET 4.0MSDN参考 ):

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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