简体   繁体   English

SwitchCase语句中的TryParse

[英]TryParse in Switch-Case Statement

I'm making a calculator, and I'm using a switch-case statement to determine what to do when the user clicks a button. 我正在制作一个计算器,并且正在使用switch-case语句来确定用户单击按钮时的操作。 When the user just presses a number (0-9) then I want to simply just add the number to the end of the current string. 当用户仅按下一个数字(0-9)时,我只想简单地将数字添加到当前字符串的末尾。 This was an easy task, although I was wondering if there's an easier way to evaluate if a string is a number in a case statement. 尽管我想知道是否存在一种更简单的方法来评估case语句中的字符串是否为数字,但这是一项容易的任务。

In other words, can I simplify the following: 换句话说,我可以简化以下内容:

case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":

//code to execute here

I know I can call TryParse earlier on and run a separate block of code, but I was wondering if there was a way to do something such as case myString.TryParse(): 我知道我可以TryParse更早的时候调用TryParse并运行一个单独的代码块,但是我想知道是否有一种方法可以执行诸如case myString.TryParse():

Thanks. 谢谢。

You are definitely going the long way around when there are simple libraries already able to handle this :) 当已经有简单的库可以处理这个问题时,您肯定会走很长一段路:)

try System.Char.IsDigit(numericChar) 试试System.Char.IsDigit(numericChar)

There are many other ways to do this easily, just google around for a bit :) 还有许多其他方法可以轻松地做到这一点,只需在Google上搜索一下即可:)

You can give it a try to use pattern matching , but I think specifying as in original post should be much faster, so I don't recommend it, but you can in fact do what you asked: 您可以尝试使用模式匹配 ,但是我认为在原始文章中指定as应该更快,因此我不建议这样做,但实际上您可以按照要求进行操作:

string a = "5";
switch (a)
{
   case var digit when char.IsDigit(a[0]):
     var intDigit = int.Parse(digit);
     ...
     break;
   ...
   <other cases>
}

Switch statements aren't suited for looking for multiple possible values, you would be better of with a bunch of if else statements Switch语句不适合查找多个可能的值,最好使用一堆if else语句

if(Char.IsDigit(inputString))
{

}
else if(someCondition)
{
}
else if(someCondition2)
{
}

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

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