你能循环遍历所有的枚举值吗? [英] Can you loop through all enum values?
本文介绍了你能循环遍历所有的枚举值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题已经在这里有一个答案:
如何枚举枚举? 14个答案
public enum Foos
{
A,
B,
C
}
有没有办法循环查看 Foos
?
基本上?
foreach(Foo in Foos)
推荐答案
是的,您可以使用GetValues方法
Yes you can use the GetValues method
var values = Enum.GetValues(typeof(Foos));
或键入版本
var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();
我很久以前为我的私人图书馆添加了一个帮助函数,只是这样一个场合
I long ago added a helper function to my private library for just such an occasion
public static class EnumUtil {
public static IEnumerable<T> GetValues<T>() {
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
用法:
var values = EnumUtil.GetValues<Foos>();
这篇关于你能循环遍历所有的枚举值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文