-5

以下程序的朋友在我编译时给了我错误。错误在StringfromMonths中。表明它在当前上下文中不存在。它在当前比赛中是如何不存在的,因为我想从枚举 Months中获取一个常量字符串,同时将其转换为字符串。

感谢您的回应!

using System;

enum Months

{

   September,
   Octobar,
   November = 11,
   December,

}

 class Montest

 {

 public static void Main()

 {

   string s;

    Console.WriteLine("Please choose a month");
    Console.WriteLine("September");
    Console.WriteLine("Octobar");
    Console.WriteLine("November");
    Console.WriteLine("December");
    s = Console.ReadLine();
    switch (s)
    {
        case "September":
            Console.WriteLine("You have selected September which has the Valuve {0}",StringfromMonths(Months.September));
            break;
        case "October":
            Console.WriteLine("You have selected September which has the Valuve {0}", StringfromMonths(Months.September));
            break;
        case "November":
            Console.WriteLine("You have selected September which has the Valuve {0}", StringfromMonths(Months.September));
            break;
        case "December":
            Console.WriteLine("You have selected September which has the Valuve {0}", StringfromMonths(Months.September));
            break;
    }


}

}
4

3 回答 3

2

您的代码中没有调用方法StringfromMonths,除了编译器错误之外,这似乎真的具有误导性,因为我认为这个丢失的方法返回一个字符串,而不是您试图打印枚举的数值Months.September......

如果你真的想打印一个枚举值的数值,你需要转换成一个整数。
所以很简单:

Console.WriteLine("You have selected September which has the value {0}", 
                   Convert.ToInt32(Months.September));

顺便说一句,如上所述,9 月的值 = 0,10 月 = 1,11 月 = 11,12 月 = 12。(所有的 switch 案例都打印 9 月?)

最后但同样重要的是,什么是“Octobar”?您订购 1 并获得 8 的酒吧?我每周六晚上都会去那里。:-))))

于 2013-04-27T13:03:21.833 回答
0

创建缺失的函数:

static public string StringfromMonths(Months months)
{
    return months.ToString();
}

但我的建议是:不要使用该功能并像这样显示您的值:

Console.WriteLine("You have selected September which has the Valuve {0}", Months.September);
于 2013-04-27T12:55:26.480 回答
0

您收到此错误是因为您没有 StringfromMonths 方法。您可以做的一件事是:

Enum.GetName(typeof(Months), Months.September):
于 2013-04-27T12:56:51.023 回答