将字符串数组转换为枚举 [英] convert array of string to enum
本文介绍了将字符串数组转换为枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个直接的解决方案,用于将字符串数组转换为枚举
i尝试了很多解决方案,但没有结果
i need a straight solution for converting array of strings to enum
i tried alot of solutions but no result
推荐答案
尝试:
Try:
enum myEnum
{
One, Two, Three
}
private void myButton_Click(object sender, EventArgs e)
{
string[] inputs = new string[] { "One", "Two", "Three" };
myEnum[] outputs = inputs.Select(i => (myEnum) Enum.Parse(typeof(myEnum), i)).ToArray();
...
我可能没有得到这个问题,但无论如何我都会对此进行抨击。
从字符串
转换为枚举
<$ c可以使用$ c> Enum.Parse 方法(或者如果你想要容错Enum.TryParse
)。
通过使用 Linq ,可以轻松地将一个数组中的所有String
转换为enum
在另一个中,如本例所示;
I'm probably not getting the question but I'm going to have a stab at this anyway.
To convert from aString
to aenum
theEnum.Parse
method can be used (or if you want to be fault tolerant theEnum.TryParse
).
By using Linq it's easy to convert allString
s in one array toenum
in the other, like in this example;
using System;
using System.Linq;
namespace Sample {
enum Fruits {
Banana,
Apple,
Orange,
Pineapple
}
class Program {
static void Main(string[] args) {
var fruitStrings = new[] {"Banana", "Apple", "Pineapple", "Orange"};
var fruits = fruitStrings.Select(fs => (Fruits)Enum.Parse(typeof (Fruits), fs));
Console.WriteLine("Strings: {0}", String.Join(", ", fruitStrings));
Console.WriteLine("Enums : {0}", String.Join(", ", fruits));
}
}
}
希望这会有所帮助,
Fredrik Bornander
Hope this helps,
Fredrik Bornander
试试这个:
Try this:
public class Problem001
{
private enum Fruits
{
Banana,
Apple,
Orange,
Pineapple
}
public Problem001()
{
string[] names = Enum.GetNames(typeof(Fruits));
for (int iIndex = 0; iIndex < names.Length; iIndex++)
{
Console.WriteLine(names[iIndex]);
}
}
}
这篇关于将字符串数组转换为枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文