C# 检查unicode字符是什么类型的字符

C# 检查unicode字符是什么类型的字符,c#,if-statement,unicode,char,C#,If Statement,Unicode,Char,我正在运行CodeEasy.net的c#程序,偶然发现了一个我正在努力解决的问题。我不明白这为什么不能通过 编写一个程序,使用以下命令从控制台读取一个字符 Console.Read()和Convert.ToChar(…)方法。在此之后 程序应输出“数字”、“字母”或“非数字和非字母” “字母”显示在屏幕上,具体取决于字符 我试过intcharCode=int.Parse(Console.ReadLine())也代替int charCode=Console.Read()但似乎什么都不起作用。它一直

我正在运行CodeEasy.net的c#程序,偶然发现了一个我正在努力解决的问题。我不明白这为什么不能通过

编写一个程序,使用以下命令从控制台读取一个字符 Console.Read()和Convert.ToChar(…)方法。在此之后 程序应输出“数字”、“字母”或“非数字和非字母” “字母”显示在屏幕上,具体取决于字符

我试过int
charCode=int.Parse(Console.ReadLine())也代替
int charCode=Console.Read()但似乎什么都不起作用。它一直给我第一个“如果”和最后一个“其他”结果,但其中只有一个应该打印出来,所以它非常混乱

以下是我目前的代码:

int charCode = Console.Read();
char theRealChar = Convert.ToChar(charCode);

if (char.IsDigit(theRealChar))
{
    Console.WriteLine("Digit");
}
if (char.IsLetter(theRealChar))
{
    Console.WriteLine("Letter");
}
else
{
    Console.WriteLine("Not a digit and not a letter");
}

非常感谢任何能帮助我理解这一点的人

如果在第二个
if
块之前添加缺少的
else
,则似乎可以正常工作

if (char.IsDigit(theRealChar))
{
    Console.WriteLine("Digit");
}
else if (char.IsLetter(theRealChar))
{
    Console.WriteLine("Letter");
}
else
{
    Console.WriteLine("Not a digit and not a letter");
}

您的
else
语句仅与第二个
if
语句关联。你实际上得到了:

if (firstCondition)
{
    // Stuff
}

// You could have unrelated code here

if (secondCondition)
{
    // Stuff
}
else
{
    // This will execute any time secondCondition isn't true, regardless of firstCondition
}
如果只希望在前面的
If
语句都不执行时执行,则需要将第二个语句设置为
else If

if (char.IsDigit(theRealChar))
{
    Console.WriteLine("Digit");
}
// Only check this if the first condition isn't met
else if (char.IsLetter(theRealChar))
{
    Console.WriteLine("Letter");
}
// Only execute this at all if neither of the above conditions is met
else
{
    Console.WriteLine("Not a digit and not a letter");
}

非常感谢。这对我来说真的很清楚:)我不知道我必须使用“else if”。谢谢你的帮助:)