积极答复者
如何将字符串转换为枚举类型,而不是枚举类型中的值?

问题
-
我定义了如下两个枚举类型
public enum ClassType
{
//内核类型
clsKernel=0,
//辅助类型
clsAssist=1,
//字典类型
clsWordBook=2
}public enum strConstType
{
//平台常量字符串
[EnumDescription("平台常量字符串")]
pltConst=0,
//平台安全过滤字符串
pltSecurity=1
}然后我将两个枚举类型的字符串:"ClassType" 和 "strConstType" 放入到一个集合出来了cllRst中
cllRst.add("ClassType")
cllRst.add("strConstType")
我打算通过遍历集合来找出上述两个枚举中的所有枚举值,这里涉及到将字符串转换为枚举类型,可以实现吗?
答案
全部回复
-
using System;
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
public enum ClassType
{
//内核类型
clsKernel = 0,
//辅助类型
clsAssist = 1,
//字典类型
clsWordBook = 2
}public enum strConstType
{
//平台常量字符串
pltConst = 0,
//平台安全过滤字符串
pltSecurity = 1
}class Program
{
static void Main(string[] args)
{
List<string> enumnames = new List<string>() { "ClassType", "strConstType" };
foreach (var item in enumnames)
{
Console.WriteLine(item+"的枚举内部数值:");foreach (var value in Enum.GetValues(Type.GetType("ConsoleApplication1." + item)))
{
Console.WriteLine(value);
}
Console.WriteLine();
}
}
}
} -
你好!
可以参考这个做法:
using System; public class ParseTest { [FlagsAttribute] enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }; public static void Main() { Console.WriteLine("The entries of the Colors Enum are:"); foreach(string s in Enum.GetNames(typeof(Colors))) Console.WriteLine(s); Console.WriteLine(); Colors myOrange = (Colors)Enum.Parse(typeof(Colors), "Red, Yellow"); Console.WriteLine("The myOrange value has the combined entries of {0}", myOrange); } }
周雪峰