當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# Type.GetEnumUnderlyingType()用法及代碼示例


Type.GetEnumUnderlyingType()方法用於返回當前枚舉類型的基礎類型。

用法:

public virtual Type GetEnumUnderlyingType ();

返回值:此方法返回當前枚舉的基礎類型。


異常:如果當前類型不是枚舉或枚舉類型無效(由於包含多個實例字段),則此方法將返回ArgumentException。

以下示例程序旨在說明上述方法的用法:

示例1:

// C# program to demonstrate the 
// Type.GetEnumUnderlyingType() Method 
using System; 
using System.Globalization; 
using System.Reflection; 
  
class GFG { 
  
    // Defining enum ABC 
    enum ABC { A, 
               B, 
               C, 
               D, 
               E, 
               F } 
  
    // Main Method 
    public static void Main() 
    { 
  
        // try-catch block to 
        // handle exceptions 
        try { 
  
            // Creating and initializing object 
            // of ABC with instace of enum ABC 
            ABC a = ABC.A; 
  
            // Declaring and initializing 
            // object of Type 
            Type type = a.GetType(); 
  
            // Getting underlying type of current enumeration 
            // By using GetEnumUnderlyingType() method 
            Type obj = type.GetEnumUnderlyingType(); 
  
            // Display underlying type 
            Console.Write("Underlying type is : {0} ", obj); 
        } 
  
        // ArgumentException here 
        catch (ArgumentException e)  
        { 
            Console.Write("The current type is not an enumeration."); 
            Console.Write("Exception Thrown: "); 
            Console.Write("{0}", e.GetType(), e.Message); 
        } 
    } 
}
輸出:
Underlying type is : System.Int32

示例2:對於ArgumentException

// C# program to demonstrate the 
// Type.GetEnumUnderlyingType() Method 
using System; 
using System.Globalization; 
using System.Reflection; 
  
class GFG { 
  
    // Defining enum ABC 
    enum ABC { A, 
               B, 
               C, 
               D, 
               E, 
               F } 
  
    // Main Method 
    public static void Main() 
    { 
  
        // try-catch block to 
        // handle exceptions 
        try { 
  
            // Declaring and initializing 
            // object of Type 
            Type type = typeof(int); 
  
            // Getting underlying type of current enumeration 
            // By using GetEnumUnderlyingType() method 
            Type obj = type.GetEnumUnderlyingType(); 
  
            // Display underlying type 
            Console.Write("underlying type is : {0} ", obj); 
        } 
  
        // catch ArgumentException here 
        catch (ArgumentException e)  
        { 
            Console.WriteLine("The current type is not an enumeration."); 
            Console.Write("Exception Thrown: "); 
            Console.Write("{0}", e.GetType(), e.Message); 
        } 
    } 
}
輸出:
The current type is not an enumeration.
Exception Thrown: System.ArgumentException

參考:



相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 C# | Type.GetEnumUnderlyingType() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。