Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chương trình C# lấy kiểu của Enumeration được chỉ định


Sử dụng phương thức GetType() để lấy kiểu của enumeration.

Enumeration:

Enum[] values = { ConsoleColor.Blue, DayOfWeek.Sunday };

Bây giờ để lấy kiểu, sử dụng phương thức GetType().

Type enumType = val.GetType();

Ví dụ sau hiển thị kiểu.

Ví dụ

using System; 

public class Demo { 
    public static void Main() { 
        Enum[] values = { ConsoleColor.Blue, DayOfWeek.Sunday }; 
        Console.WriteLine("{0,-5} {1, 10} {2,10}\n", "Member", "Enumeration", "UnderlyingType"); 
        foreach (var val in values) 
            Info(val); 
    } 
    
    static void Info(Enum val) { 
        Type enumType = val.GetType(); 
        Type underlyingType = Enum.GetUnderlyingType(enumType); 
        Console.WriteLine("{0, -5} {1, 10} {2,10}", val, enumType.Name, underlyingType.Name); 
    } 
}

Kết quả

Member  Enumeration  UnderlyingType 
Blue    ConsoleColor Int32 
Sunday  DayOfWeek    Int32