如何解决我可以检查用户是否响应然后将布尔值更新为true吗?
我想创建一段代码,如果用户通过Console.ReadLine响应,则将布尔变量设置为true。此变量稍后将在其他一些代码中使用。到目前为止,我尝试过的唯一代码是:
Dictionary<string,string,bool> loginUserData = new Dictionary<string,bool>();
loginUserData.Add("max","123",true);
我该如何进行这项工作?
作为参考,我正在使用的实际代码更像是:
bool hastyped = false;
var input = Console.ReadLine();
hastyped = true;
也就是说,在初始化变量之后。
解决方法
要查看用户是否实际输入了内容,可以检查将输入保存到的字符串。
因为当您按下Enter键时,Console.ReadLine
是一个空字符串。因此,您可以使用.IsNullOrEmpty()
进行检查,以查看输入内容实际上是否包含任何字符。
或者甚至可以使用.IsNullOrWhiteSpace()
来检查Input是否也只包含空格。
示例:
// Getting Input from Console
string input = Console.ReadLine();
// Check if Input contains more than whitespaces and isn't empty or null,// if it doesn't bool is true else it's false
bool hastyped = !string.IsNullOrWhiteSpace(input);
,
您尝试过这种方法吗?基本上,它将检查该值是否为null(如果不是),然后将其更改为true。
bool hastyped = false;
var input = Console.ReadLine();
if (input != null)
{
hastyped = true;
}
或者您也可以使用这种方式,您可以从Microsoft文档中找到有关此信息的更多信息
bool hastyped = false;
var input = Console.ReadLine();
if (!string.IsNullOrEmpty(input))
{
hastyped = true;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。