区块链学堂(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

获取最新区块链咨询,请关注《以太中文网》微信公众号:以太中文网

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值