如何在C#中使用带有字符串的开关盒?

时间:2019-03-21 20:15:46

标签: c# string switch-statement

我正在尝试制作一个非常基本的计算器程序。我收到以下错误消息:

  

不能将类型'bool'隐式转换为'string'

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _2019_03_21
{
    class Program
    {
        private static double Negyzet(int alap, int kitevo)
        {
            Console.WriteLine("Kérem a hatvány alapját!");
            alap = int.Parse(Console.ReadLine());
            Console.WriteLine("Kérem a hatvány kitevojet!");
            kitevo = int.Parse(Console.ReadLine());
            return Math.Pow(alap, kitevo);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Kérem adja meg milyen műveletet szeretne elvégezni!\n\n+ összeadás\n- kivonás\n* szorzás\n/ osztás\n^hatványozás\n\nVálasztott művelet:");
            string muvelet = Console.ReadLine();
            switch (muvelet)
            {
                case (muvelet == "^"): Console.WriteLine("A hatvány értéke:     {0}", Negyzet(0, 0)); break;
                default: break;
            }
            Console.ReadKey();
        }
    }
}

3 个答案:

答案 0 :(得分:3)

您以错误的方式使用了case子句。它需要整数或String值-但您需要提供Boolean值。但是,很容易解决该问题。像这样编写case子句:

case "^":

然后它将按预期进行编译和工作。

答案 1 :(得分:2)

muvelet是一个字符串,而muvelet == "^"是一个布尔值的comarision(它是true或false

switch(muvelet)  
{
     case "^":
         // code for when it is equal to "^"
          break;
    //other cases
    default:
         //it is unknown character
}

请注意,交换机中的类型(在这种情况下为字符串)应与案例的类型相符

答案 2 :(得分:0)

直到C#6,switch指令才保留为原始类型。现在,您可以切换到模式。

Pattern Matching

所以您可以做这种事情:

class Program
{
    static void Main(string[] args)
    {
        Print("+", 2, 2);
        Print("-", 2, 2);
        Print("/", 2, 2);
        Print("*", 2, 2);
        Print("^", 2, 2);
        Print("%", 2, 2);
        Print(" ", 2, 2);
        Print("", 2, 2);
        Console.Read();
    }
    static void Print(string op, int nmb1, int nmb2)
    {
        var res = Compute(op, nmb1, nmb2);
        Console.WriteLine(res != null ?
            $"{nmb1} {op} {nmb2} = {res}" :
            $"invalid {op?.Trim()} operator description");
    }

    static int? Compute(string op,int nmb1,int nmb2)
    {
        switch (op)
        {
            case "+":
                return nmb1 + nmb2;
            case "-":
                return nmb1 - nmb2;
            case "*":
                return nmb1 * nmb2;
            case "/":
                return nmb1 / nmb2;
            case "%":
                return nmb1 % nmb2;
            case "^":
                return nmb1 ^ nmb2;
            case var o when (o?.Trim().Length ?? 0) == 0:
                // white space
                return null;
            default:
                return null;
        }
    }
}

控制台输出:

2 + 2 = 4
2 - 2 = 0
2 / 2 = 1
2 * 2 = 4
2 ^ 2 = 0
2 % 2 = 0
invalid operator 
invalid operator