我已经阅读了文档,声明'给定枚举的类型,System.Enum的GetValues()方法将返回给定枚举的基本类型的数组'即int,byte等
但是我一直在使用GetValues方法,所有我一直回来的是一个Enums类型的数组.我错过了什么?
public enum Response
{
Yes = 1,
No = 2,
Maybe = 3
}
foreach (var value in Enum.GetValues(typeof(Response)))
{
var type = value.GetType(); // type is always of type Enum not of the enum base type
}
谢谢
the*_*oop 87
您需要将结果转换为所需的实际数组类型
(Response[])Enum.GetValues(typeof(Response))
Run Code Online (Sandbox Code Playgroud)
因为GetValues没有强类型
编辑:重新阅读答案.您需要将每个枚举值显式转换为基础类型,因为GetValues返回实际枚举类型的数组而不是基类型.Enum.GetUnderlyingType可以帮助解决这个问题.
cdm*_*kay 38
如果你使用的是.NET 3.5(即你有LINQ),你可以这样做:
var responses = Enum.GetValues(typeof(Response)).Cast<Response>();
Run Code Online (Sandbox Code Playgroud)
Joe*_*oel 12
就个人而言,我在我的Utils项目中创建了一个单独的方法,我将其包含在我的其他项目中.这是我使用的代码:
public static class EnumUtil
{
public static IEnumerable<TEnum> GetAllValues<TEnum>()
where TEnum : struct, IConvertible, IComparable, IFormattable
{
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
}
}
Run Code Online (Sandbox Code Playgroud)
我称之为:
var enumValues = EnumUtil.GetAllValues<Response>();
Run Code Online (Sandbox Code Playgroud)
你能参考你提到的文件吗?在MSDN文档上Enum.GetValues没有提到这样的(引自该网页)什么:
回报价值
键入:System.Array
enumType中常量值的数组.数组的元素按枚举常量的二进制值排序.
| 归档时间: |
|
| 查看次数: |
60118 次 |
| 最近记录: |