简体   繁体   中英

Return Enum String based on Enum Name

I have the following code which does not work but you can get an idea of what I am trying to do. I am not sure how to get a string based on the Enum. I am passing the Enum Name to the Method:

   class StateInfo
    {
        enum State{ Illinois= 0, Ohio= 1, Indiana= 2, Michigan= 3, Conneticut= 4 }; 

        static void Main(string[] args)

        {
            string result = ConvToJson("State");

        }


        public static string ConvToJson(string enumName)
        {

           Type e = Enum.GetName(typeof(enumName));

          var ret = "{";

          foreach (var val in Enum.GetValues(e))
          {
             var name = Enum.GetName(e, val);
            ret += name + ":" + ((int)val).ToString() + ",";
          }

        ret += "}";

        return ret;
     }

 }

You can use the Type.GetType Method to get the Type from a string specifying the type's name:

Type e = Type.GetType(enumName);

The name must specify the full namespace and, if the type is not in the currently executing assembly or in Mscorlib.dll, also the assembly name:

string result = ConvToJson("MyNamespace.StateInfo+State");
string result = ConvToJson("MyNamespace.StateInfo+State, MyAssembly, " +
    "Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089");

It might be easier to pass the type directly to the method:

string result = ConvToJson(typeof(State));
public static string ConvToJson(Type e)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM