错误CS0150:应为常数// // switch语句中有错误

时间:2019-06-13 21:02:53

标签: c# switch-statement

我的switch语句有问题。我不知道如何在C#中正确使用它。它给我错误CS0150,我不知道该如何处理。感谢您的帮助。谢谢。 代码被剪切。如果您看到的括号比正常情况少,请不要提醒我。

int e = 0;
string caseslol;
string multi = "multi";

Console.WriteLine("Hi there!");
Console.WriteLine("Do you want to write a number so I can do cool things with it ??");
Console.WriteLine("Write yes to say YES and no to say NO");
string str1 = Console.ReadLine();
if (str1.Contains("yes") == true)
{
    Console.WriteLine("Enter it please");
    e = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("lol, we got it!");
    Console.WriteLine("you wrote this : {0}", e);
    Console.WriteLine("Now that we got it, we can do cool stuff!");
    Console.WriteLine("Do you want to know what is this stuff ???");
    string yesorno = Console.ReadLine();
    if (yesorno.Contains("yes") == true)
    {
        Console.WriteLine("OK");
        Console.WriteLine("We can do calculating stuff with your number");
        Console.WriteLine("Soo much cool, right ???");
        string yesorno2 = Console.ReadLine();
        if (yesorno2.Contains("yes"))
        {
            Console.WriteLine("Choose first another number and write it");
            int b = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("So let's start with what ???");
            switch (caseslol) 
            {
                case multi:
                    Console.WriteLine(e * b);
            }
        }
    }

//这是输出:

error CS0150:A constant value is expected
Compilation failed: 1 error(s), 0 warnings
compiler exit status 1

2 个答案:

答案 0 :(得分:1)

您不能为case使用类似的变量,而必须使用常量。

因此,除了将变量multi放在case语句中之外,您可以使用字符串"multi"(这是您始终为变量分配的值)。

答案 1 :(得分:0)

case只能与常量一起使用。应该是

private const string multi = "multi";

switch (caseslol)
{
    case multi:
        Console.WriteLine(e * b);

        // you also need this
        break;
}

或者您直接做

switch (caseslol)
{
    case "multi":
        Console.WriteLine(e * b);

        // you also need this
        break;
}

或者您只需使用

if(string.Equals(caseslol, multi))
{
    Console.WriteLine(e * b);
}

总的来说,我看不到caseslol的位置...

相关问题