我没能转换List<string>成List<myEnumType>.我不知道为什么?
string Val = it.Current.Value.ToString(); // works well here
List<myEnumType> ValList = new List<myEnumType>(Val.Split(',')); // compile failed
Run Code Online (Sandbox Code Playgroud)
原因myEnumType类型定义为字符串枚举类型,如下所示,
public enum myEnumType
{
strVal_1,
strVal_2,
strVal_3,
}
Run Code Online (Sandbox Code Playgroud)
有什么不对的吗?感谢您的回复.
Jon*_*eet 31
编辑:哎呀,我也错过了C#2标签.我将在下面留下其他选项,但是:
在C#2中,您最好使用List<T>.ConvertAll:
List<MyEnumType> enumList = stringList.ConvertAll(delegate(string x) {
return (MyEnumType) Enum.Parse(typeof(MyEnumType), x); });
Run Code Online (Sandbox Code Playgroud)
或使用无约束旋律:
List<MyEnumType> enumList = stringList.ConvertAll(delegate(string x) {
return Enums.ParseName<MyEnumType>(x); });
Run Code Online (Sandbox Code Playgroud)
请注意,这确实假设您真的有一个List<string>开头,这对于您的标题是正确的,但对于您的问题中的正文则不正确.幸运的是Array.ConvertAll,你必须使用一个等效的静态方法,如下所示:
MyEnumType[] enumArray = Array.ConvertAll(stringArray, delegate (string x) {
return (MyEnumType) Enum.Parse(typeof(MyEnumType), x); });
Run Code Online (Sandbox Code Playgroud)
原始答案
两种选择:
在LINQ查询中使用Enum.Parse和强制转换:
var enumList = stringList
.Select(x => (MyEnumType) Enum.Parse(typeof(MyEnumType), x))
.ToList();
Run Code Online (Sandbox Code Playgroud)要么
var enumList = stringList.Select(x => Enum.Parse(typeof(MyEnumType), x))
.Cast<MyEnumType>()
.ToList();
Run Code Online (Sandbox Code Playgroud)
使用我的Unconstrained Melody项目:
var enumList = stringList.Select(x => Enums.ParseName<MyEnumType>(x))
.ToList();
Run Code Online (Sandbox Code Playgroud)