在这种情况下,如何正确使用.ToLower()
本文关键字:ToLower 何正确 这种情况下 | 更新日期: 2023-09-27 18:00:25
所以我试图让这个程序在输入时忽略用户的字母大小写。我知道如何使用.ToLower()
;然而,我不明白如何以正确的方式做到这一点。
这是我现在拥有的,我接近了吗?我在网上读过很多教程,但它们大多只是将用户输入转换为更低的独立程序。有没有办法在全球范围内实现这一点?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Choose_Your_Color
{
class Program
{
enum Color
{
red,
orange,
blue,
black,
white,
green,
purple,
yellow
}
static void Main(string[] args)
{
Color favorite;
while (true)
{
Console.WriteLine("What color do you choose?");
if (Enum.TryParse(Console.ReadLine(), out favorite))
if (string.compare(favorite , Enum , true) == 0){
Continue;
}
{
switch (favorite)
{
case Color.red:
Console.WriteLine("You chose red!");
break;
case Color.orange:
Console.WriteLine("you chose orange!!!!!!");
break;
case Color.blue:
Console.WriteLine("YOU CHOSE BLUEEEE!!");
break;
case Color.black:
Console.WriteLine("you chose black");
break;
case Color.white:
Console.WriteLine(" you chose white!");
break;
case Color.green:
Console.WriteLine("you chose green!!!!!");
break;
case Color.purple:
Console.WriteLine("you chose purple!!");
break;
case Color.yellow:
Console.WriteLine("you chose yellow!!!");
break;
}
}
else
{
Console.WriteLine("That's not a color!");
}
}
}
}
}
您只需要执行以下操作:
if (Enum.TryParse(Console.ReadLine().ToLower(), out favorite))
你不需要嵌套的if
,你可以把它删除。你还必须在if块的末尾添加一个break,这样它会在用户键入有效值后打断你的循环,否则循环永远不会结束。
Enum.TryParse
接受一个参数以忽略大小写:
Enum.TryParse(Console.ReadLine(), true, out favorite);
只需更改即可;
if (Enum.TryParse(Console.ReadLine(), out favorite))
至
if (Enum.TryParse(Console.ReadLine().ToLower(), out favorite))
Console.ReadLine()返回一个字符串,这将调用lower来降低该值,以确保所有输入都是小写的。
你为什么有这条线?
if (string.compare(favorite , Enum , true) == 0){
Continue;
}
我不认为有任何原因。Enum.TryParse
应该返回false,这意味着输入不是枚举之一,你不会进入switch语句,或者favorite
将是枚举值之一,你会进入switch声明中的一种情况。
请注意,TryParse
的重载允许您忽略输入字符串的大小写,因此您可以将其写成:
if (Enum.TryParse(Console.ReadLine(), true, out favorite))
String.ToLower()
将以小写形式返回字符串值。
if (Enum.TryParse(Console.ReadLine().ToLower(), out favorite))