C# 将字符串转换为枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13970257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:13:29  来源:igfitidea点击:

Casting string to enum

c#stringcastingenums

提问by user1765862

I'm reading file content and take string at exact location like this

我正在读取文件内容并在这样的确切位置获取字符串

 string fileContentMessage = File.ReadAllText(filename).Substring(411, 3);

Output will always be either Okor Err

输出将始终是OkErr

On the other side I have MyObjectwhich have ContentEnumlike this

在另一边我MyObject这有ContentEnum这样的

public class MyObject

    {
      public enum ContentEnum { Ok = 1, Err = 2 };        
      public ContentEnum Content { get; set; }
    }

Now, on the client side I want to use code like this (to cast my string fileContentMessageto Contentproperty)

现在,在客户端,我想使用这样的代码(将我的字符串转换fileContentMessageContent属性)

string fileContentMessage = File.ReadAllText(filename).Substring(411, 3);

    MyObject myObj = new MyObject ()
    {
       Content = /// ///,
    };

采纳答案by CodeCaster

Use Enum.Parse().

使用Enum.Parse().

var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage);

回答by Adriaan Stander

Have a look at using something like

看看使用类似的东西

Enum.TryParse

枚举.TryParse

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-sensitive. The return value indicates whether the conversion succeeded.

将一个或多个枚举常量的名称或数值的字符串表示形式转换为等效的枚举对象。参数指定操作是否区分大小写。返回值指示转换是否成功。

or

或者

Enum.Parse

枚举解析

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

将一个或多个枚举常量的名称或数值的字符串表示形式转换为等效的枚举对象。

回答by pleinolijf

As an extra, you can take the Enum.Parseanswers already provided and put them in an easy-to-use static method in a helper class.

另外,您可以采用Enum.Parse已经提供的答案,并将它们放在帮助类中易于使用的静态方法中。

public static T ParseEnum<T>(string value)
{
    return (T)Enum.Parse(typeof(T), value, ignoreCase: true);
}

And use it like so:

并像这样使用它:

{
   Content = ParseEnum<ContentEnum>(fileContentMessage);
};

Especially helpful if you have lots of (different) Enums to parse.

如果您有很多(不同的)枚举要解析,则特别有用。

回答by Chris Fulstow

.NET 4.0+ has a generic Enum.TryParse

.NET 4.0+ 有一个通用的Enum.TryParse

ContentEnum content;
Enum.TryParse(fileContentMessage, out content);