我知道如果在编译时知道枚举名称和键,如何找到枚举值。我遇到在运行时获取枚举名称的情况。任何建议如何实现这一目标。
using System;
namespace EnumDemo
{
internal class Program
{
private static void Main(string[] args)
{
string[] ArrItemNames = Enum.GetNames(typeof (EnumClass.Colors));
foreach (string ItemName in ArrItemNames)
{
Console.WriteLine(
"{0} = {1:D}", ItemName,
Enum.Parse(typeof (EnumClass.Colors), ItemName));
}
Console.WriteLine();
var EnumVal = GetEnumValue("Colors", "Red");// Here I am expecting 1
Console.ReadKey();
}
//
public static int GetEnumValue(string EnumName, string ItemName)
{
return 0;
}
}
public class EnumClass
{
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
}
}
Run Code Online (Sandbox Code Playgroud)
注意:我的枚举在一个类内。
使用Enum.Parse函数并将其转换int为此处所述
public static int GetValueOf(string enumName, string enumConst)
{
Type enumType = Type.GetType(enumName);
if (enumType == null)
{
throw new ArgumentException("Specified enum type could not be found", "enumName");
}
object value = Enum.Parse(enumType, enumConst);
return Convert.ToInt32(value);
}
Run Code Online (Sandbox Code Playgroud)
如果要在子类中为枚举调用此方法,则需要采用以下方式:
public static void Main() {
{
Console.WriteLine(GetValueOf("YourNamespace.EnumClass+Colors", "Red"));
}
Run Code Online (Sandbox Code Playgroud)
由于您知道类型,因此也可以将其直接用作:
public static void Main() {
{
Console.WriteLine(GetValueOf(typeof(EnumClass.Colors), "Red"));
}
public static int GetValueOf(Type enumType, string enumConst)
{
object value = Enum.Parse(enumType, enumConst);
return Convert.ToInt32(value);
}
Run Code Online (Sandbox Code Playgroud)