📜  Solidity-功能修改器

📅  最后修改于: 2020-11-04 04:25:57             🧑  作者: Mango


 

函数修饰符用于修改函数的行为。例如,为函数添加前提条件。

首先,我们创建带有或不带有参数的修饰符。

contract Owner {
   modifier onlyOwner {
      require(msg.sender == owner);
      _;
   }
   modifier costs(uint price) {
      if (msg.value >= price) {
         _;
      }
   }
}

将函数主体插入特殊符号“ _;”的位置出现在修饰符的定义中。因此,如果修改的条件,同时调用此函数关系成立,则执行该函数否则,抛出一个异常。

请参阅下面的示例-

pragma solidity ^0.5.0;

contract Owner {
   address owner;
   constructor() public {
      owner = msg.sender;
   }
   modifier onlyOwner {
      require(msg.sender == owner);
      _;
   }
   modifier costs(uint price) {
      if (msg.value >= price) {
         _;
      }
   }
}
contract Register is Owner {
   mapping (address => bool) registeredAddresses;
   uint price;
   constructor(uint initialPrice) public { price = initialPrice; }
   
   function register() public payable costs(price) {
      registeredAddresses[msg.sender] = true;
   }
   function changePrice(uint _price) public onlyOwner {
      price = _price;
   }
}