[SIZE=2][COLOR=#0000ff][FONT=Courier New]private [/FONT][/COLOR][/SIZE][FONT=Courier New][SIZE=2][COLOR=#0000ff]static [/COLOR][/SIZE][SIZE=2][COLOR=#008080]Type[/COLOR][/SIZE][SIZE=2] GetEnumElementType([/SIZE][SIZE=2][COLOR=#008080]Enum[/COLOR][/SIZE][/FONT][SIZE=2][FONT=Courier New] value)[/FONT][/SIZE]
[SIZE=2][FONT=Courier New]{[/FONT][/SIZE]
[FONT=Courier New][SIZE=2][COLOR=#0000ff] return[/COLOR][/SIZE][/FONT][SIZE=2][FONT=Courier New] GetEnumElementType(value.GetType());[/FONT][/SIZE]
[SIZE=2][FONT=Courier New]}[/FONT][/SIZE]
[FONT=Courier New][SIZE=2][COLOR=#0000ff]private [/COLOR][/SIZE][SIZE=2][COLOR=#0000ff]static [/COLOR][/SIZE][SIZE=2][COLOR=#008080]Type[/COLOR][/SIZE][SIZE=2] GetEnumElementType([/SIZE][SIZE=2][COLOR=#008080]Type[/COLOR][/SIZE][/FONT][SIZE=2][FONT=Courier New] enumType)[/FONT][/SIZE]
[SIZE=2][FONT=Courier New]{[/FONT][/SIZE]
[FONT=Courier New][SIZE=2][COLOR=#008080] FieldInfo[/COLOR][/SIZE][SIZE=2][] fields = enumType.GetFields([/SIZE][SIZE=2][COLOR=#008080]BindingFlags[/COLOR][/SIZE][/FONT][SIZE=2][FONT=Courier New].Public |[/FONT][/SIZE]
[FONT=Courier New][SIZE=2][COLOR=#008080]BindingFlags[/COLOR][/SIZE][/FONT][SIZE=2][FONT=Courier New].NonPublic |[/FONT][/SIZE]
[FONT=Courier New][SIZE=2][COLOR=#008080]BindingFlags[/COLOR][/SIZE][/FONT][SIZE=2][FONT=Courier New].Instance |[/FONT][/SIZE]
[FONT=Courier New][SIZE=2][COLOR=#008080]BindingFlags[/COLOR][/SIZE][/FONT][SIZE=2][FONT=Courier New].DeclaredOnly);[/FONT][/SIZE]
[FONT=Courier New][SIZE=2][COLOR=#0000ff] return[/COLOR][/SIZE][/FONT][SIZE=2][FONT=Courier New] fields[0].FieldType;[/FONT][/SIZE]
[SIZE=2][FONT=Courier New]}[/FONT][/SIZE]
Тип элемента в Enum
[FONT=Courier New][COLOR=blue]enum[/COLOR] EnumExample : [COLOR=blue]byte[/COLOR] {One = [COLOR=blue]1[/COLOR], Two = [COLOR=blue]2[/COLOR]}[/FONT]
Как бы так по нормальному узнать в runtime, какого типа его элементы (т.е. One и Two). Такой вариант:
Код:
Но что-то он кривой какой-то. Может есть у кого-то иные решения?
Код:
class Program
{
enum ShortEnum : short
{
One = 0,
Two = 1
}
enum ByteEnum : byte
{
One = 0,
Two = 1
}
static void Main(string[] args)
{
Type t = typeof(ShortEnum);
Console.WriteLine("Enum {0} has elements of type: {1}", t.Name, Enum.GetUnderlyingType(t));
t = typeof(ByteEnum);
Console.WriteLine("Enum {0} has elements of type: {1}", t.Name, Enum.GetUnderlyingType(t));
Console.ReadKey();
}
}
{
enum ShortEnum : short
{
One = 0,
Two = 1
}
enum ByteEnum : byte
{
One = 0,
Two = 1
}
static void Main(string[] args)
{
Type t = typeof(ShortEnum);
Console.WriteLine("Enum {0} has elements of type: {1}", t.Name, Enum.GetUnderlyingType(t));
t = typeof(ByteEnum);
Console.WriteLine("Enum {0} has elements of type: {1}", t.Name, Enum.GetUnderlyingType(t));
Console.ReadKey();
}
}
Результат:
Код:
Enum ShortEnum has elements of type: System.Int16
Enum ByteEnum has elements of type: System.Byte
Enum ByteEnum has elements of type: System.Byte
Спасибо