区块链学堂(23):Enum数据类型
Enums类型的官方定义
Enums are one way to create a user-defined type in Solidity. They are explicitly convertible to and from all integer types but implicit conversion is not allowed. The explicit conversions check the value ranges at runtime and a failure causes an exception. Enums needs at least one member.here
Enum类型定义
enum ActionCode {Left,Right, Forward, Rollback}
ActionCode public b2;
Enum的Demo代码
Step 1: 首先定义enum类型
pragma solidity 0.4.7;
contract Demo {enum ActionCode {Left,Right, Forward}
ActionCode public b2;
}
Step 2: 设置一个构造函数,并给变量b2赋予一个初始值
function Demo() {
b2 = ActionCode.Left;
}
Step 3:设置一个判断函数,输出结果
function f() returns (string str) {
if (b2 == ActionCode.Left) return "Left";
}
Step1-3的完整代码如下:
pragma solidity 0.4.10;
contract Demo {
enum ActionCode {Left,Right, Forward}
ActionCode public b2;
function Demo() {
b2 = ActionCode.Left;
}
function f() returns (string str) {
if (b2 == ActionCode.Left) return "Left";
}
}
Step 1-3,实现了enum(枚举)类型的功能,在构造函数中设置变量b2的初始值,然后根据b2的value来进行判断。
Step 4: 在Step1-3的基础上 添加几个function。Left()/Right()/Forward()
function Left() {
b2 = ActionCode.Left;
}
function Right() {
b2 = ActionCode.Right;
}
function Forward() {
b2 = ActionCode.Forward;
}
Step 5: 修改f(), 增加两个输出
if (b2 == ActionCode.Right) return "Right";
if (b2 == ActionCode.Forward) return "Forward";
完整代码如下:
pragma solidity 0.4.7;
contract Demo {
enum ActionCode {Left,Right, Forward}
ActionCode public b2;
function Demo() {
b2 = ActionCode.Left;
}
function Left() {
b2 = ActionCode.Left;
}
function Right() {
b2 = ActionCode.Right;
}
function Forward() {
b2 = ActionCode.Forward;
}
function f() returns (string str) {
if (b2 == ActionCode.Left) return "Left";
if (b2 == ActionCode.Right) return "Right";
if (b2 == ActionCode.Forward) return "Forward";
}
}
以上完整的代码,实现了left(),right() & forward() 方法
在Browser-solidity上的演示效果如下:
原文:http://www.ethchinese.com/?p=1044
QQ群:559649971 (区块链学堂粉丝群)
个人微信:steven_k_colin
获取最新区块链咨询,请关注《以太中文网》微信公众号:以太中文网
还没有评论,来说两句吧...