将字符串数组转换为枚举 [英] convert array of string to enum

查看:104
本文介绍了将字符串数组转换为枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个直接的解决方案,用于将字符串数组转换为枚举

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 a String to a enum the Enum.Parse method can be used (or if you want to be fault tolerant the Enum.TryParse).

By using Linq it's easy to convert all Strings in one array to enum 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆