Solidity - 回退函数

回退函数是合约可用的特殊函数。 它具有以下特点 −

  • 当合约上调用不存在的函数时,会调用它。

  • 需要标记为外部。

  • 它没有名字。

  • 它没有参数

  • 它不能返回任何东西。

  • 每个合约可以定义一个。

  • 如果没有标记为应付,如果合约收到没有数据的普通以太币,则会抛出异常。

以下示例显示了每个合约的回退函数的概念。

示例

pragma solidity ^0.5.0;

contract Test {
   uint public x ;
   function() external { x = 1; }    
}
contract Sink {
   function() external payable { }
}
contract Caller {
   function callTest(Test test) public returns (bool) {
      (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()"));
      require(success);
      // test.x is now 1

      address payable testPayable = address(uint160(address(test)));

      // Sending ether to Test contract,
      // the transfer will fail, i.e. this returns false here.
      return (testPayable.send(2 ether));
   }
   function callSink(Sink sink) public returns (bool) {
      address payable sinkPayable = address(sink);
      return (sinkPayable.send(2 ether));
   }
}