将字符串转换为枚举

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

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

输出将始终是 OkErr

另一边我有 MyObject,它有像这样的 ContentEnum

public class MyObject


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

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

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


MyObject myObj = new MyObject ()
{
Content = /// ///,
};
133270 次浏览

Use Enum.Parse().

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

Have a look at using something like

Enum.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.

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

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.

.NET 4.0+ has a generic Enum.TryParse

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