c# - 将字符串转换为枚举

标签 c# string casting enums

<分区>

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

 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 = /// ///,
    };

最佳答案

使用Enum.Parse() .

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

关于c# - 将字符串转换为枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13970257/

相关文章:

ios - 计算一些字符串 iOS 之前的字符

string - 在 Groovy Switch-Case 语句中使用静态字符串

c# - C# 中是否可以将服务结果自动转换为相同类型?

c# - Linq GroupBy - 如何在运行时指定分组键?

c# - 将 Selenium 与 Electron 框架联系起来 (c#)

c# - 派生类型和基类型区分

c# - VS2008 单元测试 - 断言方法退出

c++ - FStream 类并使用字符串作为参数

java - Array 到 List 或 List 到 Array,哪个转换更快?

ios - Swift 3 - 如何验证对象的类类型