Java开发人员的C#:枚举

枚举是一个非常普遍的概念。 当然,它也存在于Java和C#中。 但是,Java和C#枚举不具有相同的功能。 这篇博客文章旨在展示它们之间的差异。

在Java中,枚举非常类似于常规类:它们可以实现接口并具有方法。 但是,它们不能继承其他类或显式实例化。 他们可以被视为最后类(或密封已经继承了虚拟“枚举”类的C#中的类,仅具有私有构造函数和一组预定义实例(枚举的值)。

例如,让我们以HTTP状态代码为例。 在Java中,可以编写以下代码:

enum HttpStatus implements Comparable<HttpStatus> {
  OK(200), SERVER_ERROR(500), NOT_FOUND(404);

  private final int code;

  HttpStatus(int code) {
      this.code = code;
  }

  // This is a regular instance method
  int code() {
      return code;
  }

  // This is the implementation of the Comparable interface
  @Override
  int compareTo(HttpStatus o) {
      // Http statuses will be sorted by status code
      return Integer.compare(code, o.code);
  }
}
HttpStatus status = HttpStatus.OK;

// The 'code' method can be invoked like any other method
int code = status.code();

在C#中,枚举只是变相的整数。 只能使用C#模拟先前的代码段,因为码属性恰好是整型。 否则,具有相同的行为将非常复杂:

enum HttpStatus {
  // int value of the enum can be forced to a specific value
  OK = 200,
  NOT_FOUND = 404,
  SERVER_ERROR = 500
}
HttpStatus status = HttpStatus.OK;

// The enum can be casted to an int to get its value
int code = (int) status;

总而言之,Java枚举比C#枚举强大得多。 在编写Java代码时,我经常使用这些功能,如果每天都要编写C#代码,我想我会想念它们的。

from: https://dev.to//rnowif/c-for-the-java-developer-enums-2864

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值