简体   繁体   English

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

[英]How to use switch-case with strings in c#?

I'm trying to make a really basic calculator program. 我正在尝试制作一个非常基本的计算器程序。 I am getting the following error message: 我收到以下错误消息:

Cannot implicitly convert type 'bool' to 'string' 无法将类型'bool'隐式转换为'string'

Here is my code: 这是我的代码:

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();
        }
    }
}

You're using the case clause in a wrong way. 您以错误的方式使用了case子句。 It expects integer or String values - but you supply a Boolean value. 它需要整数或String值-但是您提供了Boolean值。 It's easy to fix that, however. 但是,很容易解决该问题。 Just write the case clause like that: 像这样写case子句:

case "^":

Then it should compile and work as expected. 然后它应该可以按预期进行编译和工作。

muvelet is a string while muvelet == "^" is a comarision which is boolean (it is either true or false muvelet是一个字符串,而muvelet == "^"是一个布尔运算符(它是true或false

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

note that the type in your switch (that is a string in this case) should match the type of cases 请注意,交换机中的类型(在这种情况下为字符串)应与案例的类型匹配

Until C# 6, the switch instruction was reserved for primitive types. 在C#6之前,switch指令是为基本类型保留的。 You can now switch to patterns. 您现在可以切换到模式。

Pattern Matching 模式匹配

And so you can do that kind of thing : 因此,您可以执行以下操作:

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;
        }
    }
}

console output : 控制台输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM