Construction a type would be a workaround but inacceptable for me, since it would get too complicated.
That’s the only way of getting values that will behave normally.
You can get at the fields of an open type, and the bizarre thing is that you can get values that way for enums. You should try to avoid using those values, but you can convert them to their underlying type.
public static void Main()
{
var enumType = typeof(Foo<>.Bar);
var underlyingType = Enum.GetUnderlyingType(enumType);
foreach(var field in enumType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
var value = field.GetValue(null);
var underlyingValue = Convert.ChangeType(value, underlyingType);
Console.WriteLine($"{field.Name} = {underlyingValue}");
}
}
However, a better solution is to use field.GetRawConstantValue():
public static void Main()
{
var enumType = typeof(Foo<>.Bar);
foreach(var field in enumType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
Console.WriteLine($"{field.Name} = {field.GetRawConstantValue()}");
}
}
That way if the CLR is ever fixed to prevent such weird values from ever being produced, your code won’t break.