什么是 C# 中 Java 枚举的等价物? [英] What's the equivalent of Java's enum in C#?

查看:26
本文介绍了什么是 C# 中 Java 枚举的等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 在 C# 中的枚举相当于什么?

What's the equivalent of Java's enum in C#?

推荐答案

完整的 Java 枚举功能在 C# 中不可用.不过,您可以使用嵌套类型和私有构造函数合理关闭.例如:

Full Java enum functionality isn't available in C#. You can come reasonably close using nested types and a private constructor though. For example:

using System;
using System.Collections.Generic;
using System.Xml.Linq;

public abstract class Operator
{
    public static readonly Operator Plus = new PlusOperator();
    public static readonly Operator Minus = 
         new GenericOperator((x, y) => x - y);
    public static readonly Operator Times = 
         new GenericOperator((x, y) => x * y);
    public static readonly Operator Divide = 
         new GenericOperator((x, y) => x / y);

    // Prevent other top-level types from instantiating
    private Operator()
    {
    }

    public abstract int Execute(int left, int right);

    private class PlusOperator : Operator
    {
        public override int Execute(int left, int right)
        {
            return left + right;
        }
    }

    private class GenericOperator : Operator
    {
        private readonly Func<int, int, int> op;

        internal GenericOperator(Func<int, int, int> op)
        {
            this.op = op;
        }

        public override int Execute(int left, int right)
        {
            return op(left, right);
        }
    }
}

当然,您不必使用嵌套类型,但是它们提供了 Java 枚举非常适合的方便的自定义行为"部分.在其他情况下,您只需将参数传递给私有构造函数即可获得一组众所周知的受限值.

Of course you don't have to use nested types, but they give the handy "custom behaviour" part which Java enums are nice for. In other cases you can just pass arguments to a private constructor to get a well-known restricted set of values.

这并没有给你一些东西:

A few things this doesn't give you:

  • 有序支持
  • 切换支持
  • EnumSet
  • 序列化/反序列化(作为单例)

其中一些可能可以通过足够的努力来完成,但如果没有黑客技术,切换就不会真正可行.现在,如果语言做了这样的事情,它可以通过使hackery自动化(例如自动声明const字段的负载,并更改任何将枚举类型切换为整数类型,只允许已知"情况.)

Some of that could probably be done with enough effort, though switch wouldn't really be feasible without hackery. Now if the language did something like this, it could do interesting things to make switch work by making the hackery automatic (e.g. declaring a load of const fields automatically, and changing any switch over the enum type to a switch over integers, only allowing "known" cases .)

哦,部分类型意味着您不必在同一个文件中拥有所有的枚举值.如果每个值都非常复杂(这绝对有可能),每个值都可以有自己的文件.

Oh, and partial types mean you don't have to have all of the enum values in the same file. If each value got quite involved (which is definitely possible) each could have its own file.

这篇关于什么是 C# 中 Java 枚举的等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆