W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
枚舉是在 Solidity 中創(chuàng)建用戶定義類型的一種方式。它們可以顯式轉(zhuǎn)換為所有整數(shù)類型,但不允許隱式轉(zhuǎn)換。整數(shù)的顯式轉(zhuǎn)換在運(yùn)行時檢查該值是否在枚舉范圍內(nèi), 否則會導(dǎo)致Panic 錯誤。枚舉至少需要一個成員,聲明時它的默認(rèn)值是第一個成員。枚舉不能有超過 256 個成員。
數(shù)據(jù)表示與 C 中的枚舉相同:選項由從 開始的后續(xù)無符號整數(shù)值表示0。
使用type(NameOfEnum).minandtype(NameOfEnum).max你可以獲得給定枚舉的最小值和最大值。
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.8; contract test { enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } ActionChoices choice; ActionChoices constant defaultChoice = ActionChoices.GoStraight; function setGoStraight() public { choice = ActionChoices.GoStraight; } // Since enum types are not part of the ABI, the signature of "getChoice" // will automatically be changed to "getChoice() returns (uint8)" // for all matters external to Solidity. function getChoice() public view returns (ActionChoices) { return choice; } function getDefaultChoice() public pure returns (uint) { return uint(defaultChoice); } function getLargestValue() public pure returns (ActionChoices) { return type(ActionChoices).max; } function getSmallestValue() public pure returns (ActionChoices) { return type(ActionChoices).min; } }
筆記
枚舉也可以在文件級別聲明,在合約或庫定義之外。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: