How can I reference a specific enumeration by an integer?
This question already has an answer here:
You just need to cast to your enum
:
Echemicals val = (Echemicals)i
;
But you don't need to use int[]
for this. Maybe you should give more details as to what the issue is.
我相信如果你反其道而行,先获得所有枚举并将它们转换为整数:
var enumValues = Enum.GetValues(typeof(Echemicals));
var decimals = enumValues.OfType<Echemicals>().Select(x => (int)x).ToArray();
By default, enum values in .NET are assigned integer values in order of declaration, starting at zero. Hence, with this enum...
enum Echemicals { oxygen, hydrogen, carbon }
int zero = (int)Echemicals.oxygen;
int one = (int)Echemicals.hydrogen;
int two = (int)Echemicals.carbon;
And vice versa:
Echemicals oxy = = (Echemicals)0;
But chemicals
is an array of integers, not Echemicals
. So it sounds like you want this:
int[i] = i;
If at some other time you want to convert int[2]
into the Echemicals
value corresponding to that integer value,
Echemicals chem = (Echemicals)int[2];
But if you want an array of all the Echemicals
enum values, this will work -- and it'll be more useful than that array of integers:
var echemValues = (Echemicals[])Enum.GetValues(typeof(Echemicals));
Echemicals oxy = echemValues[0];
int thisWillBeZero = (int)echemValues[0];
You can also assign the integer values explicitly when you define the enum type:
enum Echemicals { oxygen = 8, hydrogen = 1, carbon = 6 }
链接地址: http://www.djcxy.com/p/22532.html
上一篇: 如何将Integer转换为枚举值