C# If else 控制语句有两个代码块。一个是 true 块,另一个是 false 块。如果 if 块中的条件为 true,则执行 if 块中的语句;如果为 false,则执行 else 块中的语句。If Else 语句的语法如下所示。
if <condition>
{
Statements //These statements are executed if the condition is true
}
else
{
Statements //These statements are executed if the condition is false
}
C# If Else 语句示例
让我们通过判断给定的输入数字是奇数还是偶数来看一个 if else 的例子。
using System;
namespace CSharp_Tutorial
{
class Program
{
static void Main()
{
Console.WriteLine("Please enter any Numeric Value ");
int i = int.Parse(Console.ReadLine());
if (i % 2 == 0)
{
Console.WriteLine("{0} is even number", i);
}
else
{
Console.WriteLine("{0} is odd number", i);
}
}
}
}

在上面的 C# 代码中,我们使用了整型变量 i
由于 Console.ReadLine() 返回一个字符串,我们使用 Parse.int 将其显式转换为整数。

输入的数字是 93
由于 93%2 = 1,所以输出是
93 是一个奇数