C# 用户输入引用枚举

发布于 2025-01-11 06:01:04 字数 735 浏览 4 评论 0原文

这是我的作业:在您的程序中,要求用户输入月份名称。您的程序将输出该月的相应值。

所需输出的示例:

 Enter the name of a month: April

 April is month 4

这是我当前的代码。我不是程序员,而且我以某种方式颠倒了练习的要点:

class Program
{
    static void Main(string[] args)
    {

        System.Console.WriteLine("Enter the name of a month: ");
        String month1 = System.Console.ReadLine();

        Months month = (Months)Convert.ToInt32(month1);

        System.Console.WriteLine(month);


    }
}
enum Months
{
    January = 1,
    February = 2,
    March = 3,
    April = 4,
    May = 5,
    June = 6,
    July = 7,
    August = 8,
    September = 9,
    October = 10,
    November = 11,
    December = 12,

}

我的输出需要月份数,然后给出实际月份。 谢谢。

Here is my assignment: In your program, ask the user to enter the name of a month. Your program will output the corresponding value for that month.

Example of desired output:

 Enter the name of a month: April

 April is month 4

Here is my current code. I'm not a programmer, and I've somehow kind of reversed the point of the exercise:

class Program
{
    static void Main(string[] args)
    {

        System.Console.WriteLine("Enter the name of a month: ");
        String month1 = System.Console.ReadLine();

        Months month = (Months)Convert.ToInt32(month1);

        System.Console.WriteLine(month);


    }
}
enum Months
{
    January = 1,
    February = 2,
    March = 3,
    April = 4,
    May = 5,
    June = 6,
    July = 7,
    August = 8,
    September = 9,
    October = 10,
    November = 11,
    December = 12,

}

The output of mine requires the number of the month, then gives the actual month.
Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜味拾荒者 2025-01-18 06:01:04

看看 Enum.Parse 方法

备注部分中的示例甚至显示了如何处理未定义的值:

string[] colorStrings = { "0", "2", "8", "蓝色", "蓝色", "黄色", "红色, 绿色" };
      foreach(colorStrings 中的字符串 colorString)
      {
         尝试 {
            颜色 colorValue = (Colors) Enum.Parse(typeof(Colors), colorString);
            if (Enum.IsDefined(typeof(Colors), colorValue)
...

Have a look at Enum.Parse Method.

The exmple in the Remarks section even shows how to handle values that are not defined:

string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
      foreach (string colorString in colorStrings)
      {
         try {
            Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString);
            if (Enum.IsDefined(typeof(Colors), colorValue)
...
能否归途做我良人 2025-01-18 06:01:04

也许考虑完全避免枚举:

int month = DateTime.TryParse($"1 {input} 2022", out DateTime value) ? value.Month : -1;

Perhaps consider avoiding enums entirely:

int month = DateTime.TryParse(
quot;1 {input} 2022", out DateTime value) ? value.Month : -1;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文