铸造字符串枚举 [英] Casting string to enum

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

问题描述

我阅读文件内容,并采取串在准确位置这样

 字符串fileContentMessage = File.ReadAllText(文件名) .Substring(411 3); 

输出将始终为确定 ERR



在另一边,我有为MyObject 具有 ContentEnum 像这样

 公共类MyObject的

{
公共枚举ContentEnum【OK = 1,ERR = 2};
公共ContentEnum内容{搞定;组; }
}

现在,在客户端我想用这样的代码(以投我的字符串 fileContentMessage 内容属性)

 字符串fileContentMessage = File.ReadAllText(文件名).Substring(411,3); 

为MyObject MyObj中=新MyObject来()
{
含量= //////,
}; // MSDN:


解决方案

使用的 Enum.Parse()

  VAR含量=(ContentEnum)Enum.Parse(typeof运算(ContentEnum),fileContentMessage); 


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

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; }
    }

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

解决方案

Use Enum.Parse().

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

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

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