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
Casting string to enum
提问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 Ok
or Err
输出将始终是Ok
或Err
On the other side I have MyObject
which have ContentEnum
like 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 fileContentMessage
to Content
property)
现在,在客户端,我想使用这样的代码(将我的字符串转换fileContentMessage
为Content
属性)
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
看看使用类似的东西
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
或者
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.Parse
answers 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);