Enum.GetValues() 返回类型 [英] Enum.GetValues() Return Type

查看:38
本文介绍了Enum.GetValues() 返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过的文档指出给定枚举类型,System.Enum 的 GetValues() 方法将返回给定枚举基本类型的数组",即 int、byte 等

I have read documentation that states that ‘given the type of the enum, the GetValues() method of System.Enum will return an array of the given enum's base type’ ie int, byte etc

然而,我一直在使用 GetValues 方法,而我一直返回的是一个枚举类型的数组.我错过了什么吗??

However I have been using the GetValues method and all I keep getting back is an array of type Enums. Am I missing something??


public enum Response
{
    Yes = 1,
    No = 2,
    Maybe = 3
} 

foreach (Enum.GetValues(typeof(Response)) 中的 var 值){var type = value.GetType();//type 总是属于 Enum 类型而不是 enum 基类型}

foreach (var value in Enum.GetValues(typeof(Response))) { var type = value.GetType(); // type is always of type Enum not of the enum base type }

谢谢

推荐答案

您需要将结果转换为您想要的实际数组类型

You need to cast the result to the actual array type you want

(Response[])Enum.GetValues(typeof(Response))

因为 GetValues 不是强类型

as GetValues isn't strongly typed

只需重新阅读答案.您需要将每个枚举值显式转换为基础类型,因为 GetValues 返回实际枚举类型而不是基类型的数组.Enum.GetUnderlyingType 可以帮助解决这个问题.

just re-read the answer. You need to explicitly cast each enum value to the underlying type, as GetValues returns an array of the actual enum type rather than the base type. Enum.GetUnderlyingType could help with this.

这篇关于Enum.GetValues() 返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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