将字符串转换为枚举 [英] Casting string to enum

查看:242
本文介绍了将字符串转换为枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

输出将始终为 Ok Err

另一方面,我有 MyObject ContentEnum 像这样

On the other side I have MyObject which have ContentEnum like this

public class MyObject

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

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

Now, on the client side I want to use code like this (to cast my string fileContentMessage to Content property)

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

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


推荐答案

使用 Enum.Parse()

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

这篇关于将字符串转换为枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆