我可以检查用户是否响应然后将布尔值更新为 true 吗?
Can I do a check if user responds then update boolean to true?
我想创建一段代码,如果用户通过 Console.ReadLine 响应,则将布尔变量设置为 true。该变量稍后会在其他一些代码中使用。到目前为止我尝试过的唯一代码是:
bool hastyped = false;
var input = Console.ReadLine();
hastyped = true;
我怎样才能使这个工作?
作为参考,我使用的实际代码更像是:
response = Console.ReadLine();
hastyped = true;
也就是说,当然是在初始化变量之后。
要查看用户是否实际输入了某些内容,您可以检查将输入保存到的字符串。
因为当您按下 Enter 键时,Console.ReadLine
是一个空字符串。因此,您可以使用 .IsNullOrEmpty()
检查输入是否确实包含任何字符。
或者您甚至可以使用 .IsNullOrWhiteSpace()
来检查输入是否也只包含空格。
示例:
// 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;
}
或者你也可以使用这种方式,你可以从微软文档中找到更多相关信息
bool hastyped = false;
var input = Console.ReadLine();
if (!string.IsNullOrEmpty(input))
{
hastyped = true;
}
我想创建一段代码,如果用户通过 Console.ReadLine 响应,则将布尔变量设置为 true。该变量稍后会在其他一些代码中使用。到目前为止我尝试过的唯一代码是:
bool hastyped = false;
var input = Console.ReadLine();
hastyped = true;
我怎样才能使这个工作?
作为参考,我使用的实际代码更像是:
response = Console.ReadLine();
hastyped = true;
也就是说,当然是在初始化变量之后。
要查看用户是否实际输入了某些内容,您可以检查将输入保存到的字符串。
因为当您按下 Enter 键时,Console.ReadLine
是一个空字符串。因此,您可以使用 .IsNullOrEmpty()
检查输入是否确实包含任何字符。
或者您甚至可以使用 .IsNullOrWhiteSpace()
来检查输入是否也只包含空格。
示例:
// 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;
}
或者你也可以使用这种方式,你可以从微软文档中找到更多相关信息
bool hastyped = false;
var input = Console.ReadLine();
if (!string.IsNullOrEmpty(input))
{
hastyped = true;
}