关键概念
在 Solidity 中,如果在修改器中执行return,会立即终止当前函数的执行,不会执行目标函数体,但会执行修改器中_;之后的代码。
执行顺序详解
基本执行流程
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract ModifierReturn { uint256 public value; string public message; modifier withReturnCheck() { value = 1; message = "Before _"; // 如果满足条件,直接返回 if (msg.sender != address(0x123)) { value = 99; // 这会被设置 message = "Early return"; // 这会被设置 return; // 立即返回,不会执行目标函数 } _; // 如果上面没有return,这里会执行目标函数 value = 3; // 只有在没有提前return且目标函数执行完成后才会执行 message = "After _"; } function testFunction() public withReturnCheck { value = 2; message = "In function"; } }不同情况的分析
情况1:在_;前return
contract ReturnBeforeUnderscore { uint256 public step = 0; modifier mod1() { step = 1; if (true) { step = 10; return; // 立即返回 } _; // 不会执行 step = 3; // 不会执行 } function test1() public mod1 { step = 2; // 不会执行 } // 调用 test1() 后: step = 10 }情况2:在_;后return
contract ReturnAfterUnderscore { uint256 public step = 0; bool public flag = false; modifier mod2() { step = 1; _; // 执行目标函数 step = 3; if (!flag) { step = 4; return; // 提前结束修改器 } step = 5; // 不会执行 } function test2() public mod2 { step = 2; flag = true; } // 调用 test2() 后: step = 4, flag =