条件语句 #

一、条件语句概述 #

条件语句用于根据条件执行不同的代码块。C#提供了以下条件语句:

语句 说明
if 单条件判断
if-else 二选一
if-else if-else 多条件判断
switch 多分支选择

二、if语句 #

2.1 基本语法 #

csharp
if (condition)
{
}

2.2 简单示例 #

csharp
int age = 20;

if (age >= 18)
{
    Console.WriteLine("成年人");
}

bool isLoggedIn = true;
if (isLoggedIn)
{
    Console.WriteLine("欢迎回来");
}

2.3 单行语句 #

csharp
if (score >= 60)
    Console.WriteLine("及格");

if (count > 0)
    Process();

三、if-else语句 #

3.1 基本语法 #

csharp
if (condition)
{
}
else
{
}

3.2 使用示例 #

csharp
int age = 16;

if (age >= 18)
{
    Console.WriteLine("成年人");
}
else
{
    Console.WriteLine("未成年");
}

int number = -5;
if (number >= 0)
{
    Console.WriteLine("非负数");
}
else
{
    Console.WriteLine("负数");
}

3.3 嵌套if-else #

csharp
int score = 85;

if (score >= 60)
{
    if (score >= 90)
    {
        Console.WriteLine("优秀");
    }
    else if (score >= 80)
    {
        Console.WriteLine("良好");
    }
    else
    {
        Console.WriteLine("及格");
    }
}
else
{
    Console.WriteLine("不及格");
}

四、if-else if-else语句 #

4.1 基本语法 #

csharp
if (condition1)
{
}
else if (condition2)
{
}
else if (condition3)
{
}
else
{
}

4.2 使用示例 #

csharp
int score = 85;

if (score >= 90)
{
    Console.WriteLine("优秀");
}
else if (score >= 80)
{
    Console.WriteLine("良好");
}
else if (score >= 70)
{
    Console.WriteLine("中等");
}
else if (score >= 60)
{
    Console.WriteLine("及格");
}
else
{
    Console.WriteLine("不及格");
}

4.3 多条件组合 #

csharp
int age = 25;
bool hasLicense = true;

if (age >= 18 && hasLicense)
{
    Console.WriteLine("可以驾驶");
}
else if (age >= 18 && !hasLicense)
{
    Console.WriteLine("需要考取驾照");
}
else
{
    Console.WriteLine("未成年,不能驾驶");
}

五、条件运算符(三元运算符) #

5.1 基本语法 #

csharp
result = condition ? value1 : value2;

5.2 使用示例 #

csharp
int age = 20;
string status = age >= 18 ? "成年" : "未成年";

int number = -5;
int abs = number >= 0 ? number : -number;

int a = 10, b = 20;
int max = a > b ? a : b;
int min = a < b ? a : b;

5.3 嵌套三元运算符 #

csharp
int score = 85;
string grade = score >= 90 ? "A" :
               score >= 80 ? "B" :
               score >= 70 ? "C" :
               score >= 60 ? "D" : "F";

六、模式匹配 #

6.1 类型模式 #

csharp
object obj = "Hello";

if (obj is string s)
{
    Console.WriteLine($"字符串长度:{s.Length}");
}

if (obj is int n)
{
    Console.WriteLine($"整数:{n}");
}

6.2 属性模式 #

csharp
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

var person = new Person { Name = "张三", Age = 25 };

if (person is { Age: >= 18 })
{
    Console.WriteLine("成年人");
}

if (person is { Name: "张三", Age: var age })
{
    Console.WriteLine($"张三,{age}岁");
}

6.3 组合模式 #

csharp
object value = 42;

if (value is int and > 0 and < 100)
{
    Console.WriteLine("正整数且小于100");
}

if (value is int or double)
{
    Console.WriteLine("数值类型");
}

if (value is not null)
{
    Console.WriteLine("非空");
}

七、实战示例 #

7.1 成绩等级判断 #

csharp
public static string GetGrade(int score)
{
    if (score < 0 || score > 100)
        return "无效分数";
    
    if (score >= 90) return "优秀";
    if (score >= 80) return "良好";
    if (score >= 70) return "中等";
    if (score >= 60) return "及格";
    return "不及格";
}

7.2 闰年判断 #

csharp
public static bool IsLeapYear(int year)
{
    if (year % 400 == 0)
        return true;
    if (year % 100 == 0)
        return false;
    if (year % 4 == 0)
        return true;
    return false;
}

public static bool IsLeapYear2(int year)
{
    return (year % 400 == 0) || (year % 100 != 0 && year % 4 == 0);
}

7.3 用户登录验证 #

csharp
public static LoginResult ValidateLogin(string username, string password)
{
    if (string.IsNullOrEmpty(username))
        return LoginResult.UsernameEmpty;
    
    if (string.IsNullOrEmpty(password))
        return LoginResult.PasswordEmpty;
    
    if (username.Length < 3)
        return LoginResult.UsernameTooShort;
    
    if (password.Length < 6)
        return LoginResult.PasswordTooShort;
    
    var user = UserRepository.FindByUsername(username);
    if (user == null)
        return LoginResult.UserNotFound;
    
    if (!user.VerifyPassword(password))
        return LoginResult.PasswordIncorrect;
    
    if (!user.IsActive)
        return LoginResult.AccountDisabled;
    
    return LoginResult.Success;
}

7.4 日期验证 #

csharp
public static bool IsValidDate(int year, int month, int day)
{
    if (year < 1 || year > 9999)
        return false;
    
    if (month < 1 || month > 12)
        return false;
    
    int maxDay = month switch
    {
        2 => DateTime.IsLeapYear(year) ? 29 : 28,
        4 or 6 or 9 or 11 => 30,
        _ => 31
    };
    
    return day >= 1 && day <= maxDay;
}

八、最佳实践 #

8.1 使用大括号 #

csharp
if (condition)
{
    DoSomething();
}

if (condition)
    DoSomething();

8.2 避免深层嵌套 #

csharp
if (user == null)
    return;

if (!user.IsActive)
    return;

if (!user.HasPermission)
    return;

ProcessUser(user);

if (user != null)
{
    if (user.IsActive)
    {
        if (user.HasPermission)
        {
            ProcessUser(user);
        }
    }
}

8.3 正向条件优先 #

csharp
if (IsValid())
{
    Process();
}

if (!IsValid())
{
    return;
}
Process();

8.4 提取复杂条件 #

csharp
bool isAdult = age >= 18;
bool hasValidId = id != null && id.IsValid;
bool hasPayment = creditCard != null || paypal != null;

if (isAdult && hasValidId && hasPayment)
{
    ProcessOrder();
}

九、总结 #

条件语句要点:

语句 说明
if 单条件判断
if-else 二选一
if-else if-else 多条件判断
?: 三元运算符
is 模式匹配

下一步,让我们学习switch语句!

最后更新:2026-03-26