什么是Java的枚举在C#中的相同呢? [英] What's the equivalent of Java's enum in C#?

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

问题描述

什么是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

  • 序列化/反序列化(如单身)

  • Ordinal support
  • Switch support
  • EnumSet
  • Serialization/deserialization (as a singleton)

有的那也许可以用足够的精力完成的,但开关不会真的是可行的,而不两轮牛车。现在,如果的语言的做了这样的事情,它可以做有趣的事情通过使两轮牛车自动进行开关工作(例如声明常量的负载自动领域,改变了枚举类型的开关,在整数一个开关,只允许已知的情况。)

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.

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

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