現在の列挙型C#の基になる型を取得します
現在の列挙型の基になる型を返すためのコードは次のとおりです-
例
using System;
public class Demo {
enum Vehicle {Car, Bus, Bike, Airplane}
public static void Main() {
try {
Vehicle v = Vehicle.Bike;
Type type = v.GetType();
string[] str = type.GetEnumNames();
Console.WriteLine("GetEnumName() to return the constant name = " + str);
Type type2 = type.GetEnumUnderlyingType();
Console.Write("Enum Underlying type = "+type2);
Console.WriteLine("\nListing constants ..");
for (int i = 0; i < str.Length; i++)
Console.Write("{0} ", str[i]);
}
catch (ArgumentException e) {
Console.WriteLine("Not an enum!");
Console.Write("{0}", e.GetType(), e.Message);
}
}
} 出力
これにより、次の出力が生成されます-
GetEnumName() to return the constant name = System.String[] Enum Underlying type = System.Int32 Listing constants .. Car Bus Bike Airplane
例
別の例を見てみましょう-
using System;
public class Demo {
enum Vehicle {Car, Bus, Bike, Airplane}
public static void Main() {
try {
Type type = typeof(int);
string[] str = type.GetEnumNames();
Console.WriteLine("GetEnumName() to return the constant name = " + str);
Type type2 = type.GetEnumUnderlyingType();
Console.Write("Enum Underlying type = "+type2);
Console.WriteLine("\nListing constants ..");
for (int i = 0; i < str.Length; i++)
Console.Write("{0} ", str[i]);
}
catch (ArgumentException e) {
Console.WriteLine("Not an enum!");
Console.Write("{0}", e.GetType(), e.Message);
}
}
} 出力
これにより、次の出力が生成されます-
Not an enum! System.ArgumentException
-
C#で現在のインスタンスのタイプを取得する
現在のインスタンスのタイプを取得するためのコードは次のとおりです- 例 using System; public class Demo { public static void Main(){ string s = "Demo"; Console.WriteLine("String = " +s); Console.WriteLine("String Type = " +s.GetTy
-
指定された列挙型のタイプを取得するC#プログラム
GetType()メソッドを使用して、列挙型のタイプを取得します。 列挙。 Enum[] values = { ConsoleColor.Blue, DayOfWeek.Sunday}; 次に、型を取得するには、GetType()メソッドを使用します。 Type enumType = val.GetType(); 以下は、タイプを表示する例です。 例 using System; public class Demo { public static void Main() { Enum[] values = { Consol