字符串到c#中的枚举值

时间:2015-08-14 13:30:42

标签: c# enums

我的枚举定义如下。

 public enum Places : long
  {
    World = (long)1,
    India = (long)23424848,
    USA = (long)23424977
  }

现在我得到一串像印度'的价值。我想要枚举器的相应值。

例如,如果我得到字符串' World'(或世界不区分大小写),我需要返回值1。

我试过这种方式:

long woeid = ((long)(typeof(Places)country)); 

这不起作用。

有简单的方法吗?

1 个答案:

答案 0 :(得分:3)

您想要的方法是Enum.Parse

您可以这样使用它:

string country = "India";
Places myplace = (Places)Enum.Parse(typeof(Places), country);
long placeID = (long)Enum.Parse(typeof(Places), country);