【问题标题】:Determine underlying integral type of an Enum in C# [duplicate]在C#中确定枚举的基础整数类型[重复]
【发布时间】:2014-06-28 17:32:50
【问题描述】:

考虑以下枚举:

enum TestSByte:  sbyte  { Value1, Value2, }
enum TestInt16:  short  { Value1, Value2, }
enum TestInt32:  int    { Value1, Value2, }
enum TestInt64:  long   { Value1, Value2, }
enum TestByte:   byte   { Value1, Value2, }
enum TestUInt16: ushort { Value1, Value2, }
enum TestUInt32: uint   { Value1, Value2, }
enum TestUInt64: ulong  { Value1, Value2, }

var types = new Type []
{
    typeof(TestSByte),
    typeof(TestInt16),
    typeof(TestInt32),
    typeof(TestInt64),
    typeof(TestByte),
    typeof(TestUInt16),
    typeof(TestUInt32),
    typeof(TestUInt64),
};

foreach (var type in types)
{
    Console.WriteLine("Type: {0} - {1}.", type.Name, type.BaseType.Name);
}

输出:

Type: TestSByte - Enum.
Type: TestInt16 - Enum.
Type: TestInt32 - Enum.
Type: TestInt64 - Enum.
Type: TestByte - Enum.
Type: TestUInt16 - Enum.
Type: TestUInt32 - Enum.
Type: TestUInt64 - Enum.

我真正想要的是确定每个 Enum 的基础整数类型是什么。在监视窗口中浏览类型定义时,我找不到任何相同的指示。请指教。

【问题讨论】:

    标签: c# .net inheritance enums enumeration


    【解决方案1】:

    你可以使用Enum.GetUnderlyingType:

    Console.WriteLine("Type: {0} - {1}.", type.Name, Enum.GetUnderlyingType(type).Name);
    

    【讨论】:

    • 谢谢。我正在尝试type.BaseTypetype.UnderlyingSystemType。除了你提到的静态方法,我还偶然发现了实例方法type.GetEnumUnderlyingType()
    • Enum 的底层类型不总是int 吗?如果不是,您是否真的希望它是,因为框架中的每个 Enum 似乎都是底层类型intmsdn.microsoft.com/en-us/library/…
    • @RobertHarvey:Enum 的基础类型默认为Int32,但可以是除char 之外的任何整数类型。在许多情况下,Int32 以外的类型会很有用(例如无符号类型)。就我而言,我将代码编写为通用类库,因此需要在合理范围内处理所有可能的情况。
    猜你喜欢
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2018-07-04
    • 2016-11-30
    相关资源
    最近更新 更多