How can I get an enum name from the name of the enum type and an int

This question already has an answer here:

  • Cast int to enum in C# 21 answers
  • Convert String to Type in C# [duplicate] 4 answers
  • Enum String Name from Value 6 answers
  • Get the name of Enum value 3 answers
  • Get enum name when value is known 6 answers

  • In addition to the name of enum itself you should know namespace and assembly that enum is declared at. Assuming you run code below in assembly where enum is defined and all your enums are defined in the same namespace you know at compile time, you can do it like that:

    string dataType = "Cheese";
    int dataValue = 3;
    var enumType = Type.GetType("Namespaces.Of.Your.Enums." + dataType);
    var name = Enum.GetName(enumType, dataValue);
    

    If your enum is in another assembly than this code is running at - you will need to provide assembly qualified name of your enum type (again with namespace).


    Type t = Type.GetType(dataType)
    string value = Enum.GetName(t, dataValue)
    

    应该做的伎俩(未编译,在地铁上)


    enum.Parse() would be your friend here.

    Like so:

    int cheeseType = 1;
    (Cheese)Enum.Parse(typeof(Cheese), cheeseType.ToString());
    
    链接地址: http://www.djcxy.com/p/22524.html

    上一篇: 将方法参数转换为枚举

    下一篇: 我如何从枚举类型的名称和int获取枚举名称