Enum value to string

前端 未结 6 1816
无人共我
无人共我 2021-02-06 21:59

Does anyone know how to get enum values to string?

example:

private static void PullReviews(string action, HttpContext context)
{
    switch (action)
            


        
6条回答
  •  野性不改
    2021-02-06 22:42

    public enum Color
    {
        Red
    }
    
    var color = Color.Red;
    var colorName = Enum.GetName(color.GetType(), color); // Red
    

    Edit: Or perhaps you want..

    Enum.Parse(typeof(Color), "Red", true /*ignorecase*/); // Color.Red
    

    There is no TryParse for Enum, so if you expect errors, you have to use try/catch:

    try
    {
      Enum.Parse(typeof(Color), "Red", true /*ignorecase*/);
    }
    catch( ArgumentException )
    {
      // no enum found
    }
    

提交回复
热议问题