简体   繁体   English

c#中的变量integer如何获取枚举中的特定项?

[英]How do you get a specific item in an enumeration by a variable integer in c#?

I have this enumeration list我有这个枚举列表

enum Month
{
    January = 1,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December
}

I am gathering an integer from the console named input with a value of 1-12.我正在从名为 input 的控制台收集一个 integer,其值为 1-12。 How do I make it print out the corresponding month?如何让它打印出相应的月份? Eg:1 = January, 6=June.例如:1 = 一月,6 = 六月。

Thank you for your time and help!感谢您的宝贵时间和帮助!

You can cast the int to your Enum您可以将int转换为您的枚举

var m = (Month)1;

Console.WriteLine(m.ToString());

But bear in mind if the enum value isn't defined it will simply print the int.但请记住,如果未定义枚举值,它只会打印 int。

Alternatively you can use或者你可以使用

var m = Enum.GetName(typeof(Month), 1);

which will return null if it isn't defined如果未定义,它将返回null

I invite you to read the documentation about enums我邀请您阅读有关枚举的文档

And here is the answer to your question:这是您问题的答案:

var input = Console.ReadLine();
int enumIntValue = int.Parse(input); // You can also use TryParse (safer).
Month month = (Month) enumIntValue; // You can use Enum.IsDefined before to check if the int value is valid for the enum. 
Console.WriteLine(month); // print out the month.

Read also: TryParse , Enum.IsDefined另请阅读: TryParseEnum.IsDefined

For information purposes, to see all of the textual values in an enum, you can get the values like so...出于信息目的,要查看枚举中的所有文本值,您可以获得这样的值......

static void Main(string[] args)
{
    var enumValues = Enum.GetValues(typeof(Month));

    foreach (var enumValue in enumValues)
        Console.WriteLine(enumValue);
}

You can convert the integer value to the corresponding Enum via a cast, and then get its string representation:您可以通过强制转换将 integer 值转换为相应的 Enum,然后获取其字符串表示形式:

var monthEnum = (Month)yourIntValue;
var strEnum = monthEnum.ToString();

Note that if yourIntValue isn't a valid enum value (eg 0, or 13), then the program will still run, but will output the integer value.请注意,如果您的yourIntValue不是有效的枚举值(例如 0 或 13),则程序仍将运行,但 output 将变为 integer 值。

Also note that a better way to get a month's name would be to use the CultureInfo class :另请注意,获取月份名称的更好方法是使用CultureInfo class

// the current culture info, from your computer
var culture = CultureInfo.CurrentCulture; 

// you can also specify a known culture 
culture = CultureInfo.GetCultureInfo("en")
var monthName = culture.DateTimeFormat.GetMonthName(yourIntValue);
var input= Console.ReadLine();
Month month = 0;
if (Enum.TryParse(input, out month)) //Using try parse is safer
{
Console.WriteLine(month.ToString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM