[英]How do you get a specific item in an enumeration by a variable integer in c#?
我有這個枚舉列表
enum Month
{
January = 1,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}
我正在從名為 input 的控制台收集一個 integer,其值為 1-12。 如何讓它打印出相應的月份? 例如:1 = 一月,6 = 六月。
感謝您的寶貴時間和幫助!
您可以將int
轉換為您的枚舉
var m = (Month)1;
Console.WriteLine(m.ToString());
但請記住,如果未定義枚舉值,它只會打印 int。
或者你可以使用
var m = Enum.GetName(typeof(Month), 1);
如果未定義,它將返回null
我邀請您閱讀有關枚舉的文檔
這是您問題的答案:
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.
另請閱讀: TryParse , Enum.IsDefined
出於信息目的,要查看枚舉中的所有文本值,您可以獲得這樣的值......
static void Main(string[] args)
{
var enumValues = Enum.GetValues(typeof(Month));
foreach (var enumValue in enumValues)
Console.WriteLine(enumValue);
}
您可以通過強制轉換將 integer 值轉換為相應的 Enum,然后獲取其字符串表示形式:
var monthEnum = (Month)yourIntValue;
var strEnum = monthEnum.ToString();
請注意,如果您的yourIntValue
不是有效的枚舉值(例如 0 或 13),則程序仍將運行,但 output 將變為 integer 值。
另請注意,獲取月份名稱的更好方法是使用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.