如何在c#中检查输入的类型并使用if.else条件而不出错



我在做一个项目,你必须输入密码。

using System;
namespace program.cs
{
class Program
{
static void Main(string[] args)
{
bool checkpoint1 = false;
long password = 99101L;
Console.WriteLine("Write the Password to Access");
string keyPassword = Console.ReadLine();
if(keyPassword.Length != 0)
{
checkpoint1 = true;
}
else
{
Console.WriteLine("The Password you entered was blank.");
}

if (checkpoint1)
{
long key = Convert.ToInt64(keyPassword);
if (key == password)
{
Console.WriteLine("Access Granted!");
}
else
{
Console.WriteLine("Password Incorrect! n Access Denied");
}
}
}
}
}

但是,当我输入一个字符串作为密码时,它会在long key = Conver.ToInt64(keyPassword)行上抛出一个错误,即它不能更改为long,所以我如何解决这个问题,它会打印出类型是字符串,如果我尝试getType和typeof((,它会显示一个字符串,无论readline总是在字符串中使用什么。请帮忙。编辑:我解决了它,最终结果代码:

using System;
namespace program.cs
{
class Program
{
static void Main(string[] args)
{
bool checkpoint1 = false;
long password = 99101L;
Console.WriteLine("Write the Password to Access");
string keyPassword = Console.ReadLine();
if(keyPassword.Length != 0)
{
checkpoint1 = true;
}
else
{
Console.WriteLine("The Password you entered was blank.");
}

if (checkpoint1)
{
if(!long.TryParse(keyPassword, out var key))
{
Console.WriteLine("The Password you entered is not a number, please try again");
}
else
{
long Realkey = Convert.ToInt64(keyPassword);
if (Realkey == password)
{
Console.WriteLine("Access Granted!");
}
else
{
Console.WriteLine("Password Incorrect! n Access Denied");
}
}
}
}
}
}

您可以使用long。TryParse:

string keyPassword = Console.ReadLine();
if (string.IsNullOrEmpty(keyPassword)) {
Console.WriteLine("The Password you entered was blank.");
} 
else if (!long.TryParse(keyPassword, out var key)) {
Console.WriteLine("The Password you entered is not a valid integer.");
}  
else if (key != password) {
Console.WriteLine("Password Incorrect! n Access Denied");
}
else { // Ugh, finally...
Console.WriteLine("Access Granted!");
}

最新更新