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