繁体   English   中英

如何使用 Enum.GetValues() 方法的结果?

[英]How to use the result of Enum.GetValues() method?

我是 c# 的新手。 我想知道如何将 Enum.GetValues() 方法的结果转换为字符串数组? 这是我的代码:

using System;
using System.Linq;
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (var item in Enum.GetValues(typeof(MyEnumList)))
                Console.WriteLine(item);
        }
    }
    public enum MyEnumList
    {
        egg, apple, orange, potato
    }
}

现在我不想对结果进行 foreach 。 我想将结果存储为 string[] 变量。 谢谢你。

如果你想要一个名称数组,你可以使用Enum.GetNames方法

检索指定枚举中常量名称的数组。

using System;
                    
public class Program
{
    public static void Main()
    {
        string[] names = Enum.GetNames(typeof(MyEnumList));
        Console.WriteLine("[{0}]", string.Join(",", names));
    }
}
public enum MyEnumList
{
    egg, apple, orange, potato
}

output

[鸡蛋、苹果、橙子、土豆]


如果你想要一个数字值的string[]

using System;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        string[] enumAsStrings = Enum.GetValues(typeof(MyEnumList)) // strongly typed values
                                     .Cast<int>() // Get the _numeric_ values
                                     .Select(x => x.ToString()) // conv. to string
                                     .ToArray(); // give me an array
        Console.WriteLine("[{0}]",string.Join(",", enumAsStrings));
    }
}
public enum MyEnumList
{
    egg, apple, orange, potato
}

output

[0,1,2,3]

可能你想要这样的东西:

    var enums = Enum.GetValues(typeof(MyEnumList)).Cast<MyEnumList>().Select(x=>x.ToString()).ToArray();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM