区块链学堂(23):Enum数据类型

﹏ヽ暗。殇╰゛Y 2022-06-02 05:36 307阅读 0赞

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类型定义

  1. enum ActionCode {Left,Right, Forward, Rollback}
  2. ActionCode public b2;

Enum的Demo代码

  • Step 1: 首先定义enum类型

    pragma solidity 0.4.7;
    contract Demo {

    1. enum ActionCode {Left,Right, Forward}
    2. ActionCode public b2;

    }

  • Step 2: 设置一个构造函数,并给变量b2赋予一个初始值

    1. function Demo() {
    2. b2 = ActionCode.Left;
    3. }
  • Step 3:设置一个判断函数,输出结果

    1. function f() returns (string str) {
    2. if (b2 == ActionCode.Left) return "Left";
    3. }
Step1-3的完整代码如下:
  1. pragma solidity 0.4.10;
  2. contract Demo {
  3. enum ActionCode {Left,Right, Forward}
  4. ActionCode public b2;
  5. function Demo() {
  6. b2 = ActionCode.Left;
  7. }
  8. function f() returns (string str) {
  9. if (b2 == ActionCode.Left) return "Left";
  10. }
  11. }
Step 1-3,实现了enum(枚举)类型的功能,在构造函数中设置变量b2的初始值,然后根据b2的value来进行判断。
  • Step 4: 在Step1-3的基础上 添加几个function。Left()/Right()/Forward()

    1. function Left() {
    2. b2 = ActionCode.Left;
    3. }
    4. function Right() {
    5. b2 = ActionCode.Right;
    6. }
    7. function Forward() {
    8. b2 = ActionCode.Forward;
    9. }
  • Step 5: 修改f(), 增加两个输出

    1. if (b2 == ActionCode.Right) return "Right";
    2. if (b2 == ActionCode.Forward) return "Forward";
完整代码如下:
  1. pragma solidity 0.4.7;
  2. contract Demo {
  3. enum ActionCode {Left,Right, Forward}
  4. ActionCode public b2;
  5. function Demo() {
  6. b2 = ActionCode.Left;
  7. }
  8. function Left() {
  9. b2 = ActionCode.Left;
  10. }
  11. function Right() {
  12. b2 = ActionCode.Right;
  13. }
  14. function Forward() {
  15. b2 = ActionCode.Forward;
  16. }
  17. function f() returns (string str) {
  18. if (b2 == ActionCode.Left) return "Left";
  19. if (b2 == ActionCode.Right) return "Right";
  20. if (b2 == ActionCode.Forward) return "Forward";
  21. }
  22. }
以上完整的代码,实现了left(),right() & forward() 方法

在Browser-solidity上的演示效果如下:

import_enum_01.png


原文:http://www.ethchinese.com/?p=1044

QQ群:559649971 (区块链学堂粉丝群)
个人微信:steven_k_colin

stevenkcolin.jpg

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

ethchinese.jpg

发表评论

表情:
评论列表 (有 0 条评论,307人围观)

还没有评论,来说两句吧...

相关阅读