提前返回
本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 18 课,共 66 课。
提前返回是一种技巧,当我们得到答案或遇到无效条件时,就立即退出方法,而不是嵌套条件语句。
我们来比较两种验证用户名的方法:
不使用提前返回(嵌套条件语句):
public bool ValidateUsername(string username)
{
bool isValid = false;
if (username != null)
{
if (username.Length >= 3)
{
if (username.Length <= 20)
{
isValid = true;
}
}
}
return isValid;
}使用提前返回:
public bool ValidateUsername(string username)
{
// 如果 username 为 null,就提前返回
if (username == null)
return false;
// 如果 username 太短,就提前返回
if (username.Length < 3)
return false;
// 如果 username 太长,就提前返回
if (username.Length > 20)
return false;
// 如果执行到这里,说明 username 有效
return true;
}提前返回可以让代码更易读,并减少缩进层级。
挑战
简单编写一个名为 ProcessPayment 的方法,根据以下条件判断是否可以处理付款:
- 付款金额必须为正数
- 账户余额必须充足
- 账户不能处于锁定状态
使用提前返回来检查每个条件,并返回相应的错误消息。
该方法应:
- 接收三个参数:
decimal paymentAmount、decimal accountBalance和bool isAccountLocked - 返回一个字符串,内容为 "Payment processed successfully" 或错误消息
- 使用提前返回进行验证
错误消息必须严格采用以下格式:
- "Error: Payment amount must be positive"
- "Error: Insufficient funds"
- "Error: Account is locked"
亲手试试
using System;
public class Program
{
public static string ProcessPayment(decimal paymentAmount, decimal accountBalance, bool isAccountLocked)
{
// 在这里编写你的代码
}
public static void Main(string[] args)
{
decimal paymentAmount = decimal.Parse(Console.ReadLine());
decimal accountBalance = decimal.Parse(Console.ReadLine());
bool isAccountLocked = bool.Parse(Console.ReadLine());
string result = ProcessPayment(paymentAmount, accountBalance, isAccountLocked);
Console.WriteLine(result);
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: C# 在线编译器