23-02-25

First Post:

Last Update:

2023-02-25

Enum 枚举

一个合约可以有多个枚举

1
2
3
4
5
6
pragma solidity ^0.8.0;

contract Example {
enum Status { Pending, Approved, Rejected }
enum Color { Red, Green, Blue }
}

枚举的相关赋值方法以及重置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//文件:test_enum.sol

pragma solidity ^0.8.17;
// SPDX-License-Identifier: mit
import "./enum.sol"; //可以直接引入文件
contract status {
enum state{
pending,
shipped,
accepted,
rejected,
canceled
}
enum testa{
aaaed,
bbbed,
ced
}
state public ss;

function get() public view returns(state) {
return ss;
}
function setState(state stt) public {
ss = stt;
}
function cancel() public {
ss = state.canceled;
}
function reset() public {
delete ss;//会重置为零
}
function setStateByNum(uint index) public {
ss = state(index);//根据索引进行赋值
}
function test() public returns(bool) {
setStateByNum(1);
return (ss==state.shipped);
}

}

//文件:enum.sol

pragma solidity ^0.8.17;
//SPDX-License-Identifier: MIT
enum _status {
Pending,
Shipped,
Accepted,
Rejected,
Canceled
}