2017-07-08 20 views

回答

7

修飾符允許您將附加功能包裝到方法中,因此它們有點像OOP中的修飾器模式。

修飾符通常用於智能合約中,以確保在繼續執行方法中的其他代碼體之前滿足某些條件。

例如,isOwner經常被用來確保該方法的調用者是合同的業主:

modifier isOwner() { 
    if (msg.sender != owner) { 
     throw; 
    } 

    _; // continue executing rest of method body 
} 

doSomething() isOwner { 
    // will first check if caller is owner 

    // code 
} 

您還可以堆疊多個修飾符來簡化你的程序:

enum State { Created, Locked, Inactive } 

modifier isState(State _state) { 
    require(state == _state); 

    _; // run rest of code 
} 

modifier cleanUp() { 
    _; // finish running rest of method body 

    // clean up code 
} 

doSomething() isOwner isState(State.Created) cleanUp { 
    // code 
} 

修飾符用聲明和可讀的方式表示正在發生的操作。

相關問題