现在的位置: 首页 > 综合 > 正文

Convert a string to an enum

2013年12月26日 ⁄ 综合 ⁄ 共 654字 ⁄ 字号 评论关闭

 Convert a string to an enum. (string转enum)
I encountered a problem when coding where I wanted to convert a string to an enum last night, First, I generated a long list of switch and case statements to handle this problem. But it is very awkward, so I tried to find a simple way to do it, finally I got it.
    Sample code as below :

     enum NodeType { RootNode, CorpNode, CentralNode, DepartmentNode }

     public class OrganizeNode
     {
         public static NodeType getNodeType(string strNodeName)
         {
              NodeType nodeType;
              nodeType = (NodeType) NodeType.Parse(typeof(NodeType), strNodeName, true);
              return nodeType;
         }
     }

try it:

nodetype = (nodetype)Enum.Parse(typeof(NodeType),strNodeName,true);

抱歉!评论已关闭.