如何在 C# 中获取所有枚举值的数组? [英] How to get an array of all enum values in C#?
本文介绍了如何在 C# 中获取所有枚举值的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个枚举,我想显示所有可能的值.有没有办法获取枚举的所有可能值的数组或列表,而不是手动创建这样的列表?例如如果我有一个枚举:
I have an enum that I'd like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating such a list? e.g. If I have an enum:
public enum Enumnum { TypeA, TypeB, TypeC, TypeD }
我如何获得包含 { TypeA, TypeB, TypeC, TypeD }
的 List
?
how would I be able to get a List<Enumnum>
that contains { TypeA, TypeB, TypeC, TypeD }
?
推荐答案
这会使用 Enum.GetValues
:
var valuesAsArray = Enum.GetValues(typeof(Enumnum));
这会为您提供一个通用列表:
And this gets you a generic list:
var valuesAsList = Enum.GetValues(typeof(Enumnum)).Cast<Enumnum>().ToList();
这篇关于如何在 C# 中获取所有枚举值的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文