【问题标题】:Enums in Java VS Enums in C# [duplicate]Java中的枚举与C#中的枚举[重复]
【发布时间】:2020-05-10 17:47:36
【问题描述】:

我有一个非常基本的问题。在Java中,可以将属性和变量指向Enums,例如:

public enum DayTime{
    Morning("Morning"),
    Afternoon("Afternoon"),
    Night("Night");

    private string description;

    Daytime(string description){
        this.description = description;
    }

    public string getDescription(){
        return description;
    }
}

是否可以将相同的概念应用于 C#?我正在尝试对产品进行模块化描述,而它们的名称、内容和特征将显示在一串文本中,而 Enums 看起来是根据选择的特征修改此文本的最佳选择。

【问题讨论】:

  • @OmairMajid 不,但这是一个有趣的观点。
  • 这能回答你的问题吗? C# vs Java Enum (for those new to C#)
  • 有点糟糕的示例代码。首先,您应该对枚举常量使用全部大写。其次,name() 已经返回了常量的名称,所以你只需要稍微改变一下大小写。

标签: java c# enums


【解决方案1】:

与 Java 枚举相比,C# 枚举非常基础。如果你想模拟同样的行为,你需要使用一个带有内部枚举的类:

using System.Collections.Generic;

public sealed class DayTime
{
    public static readonly DayTime Morning = new DayTime("Morning", InnerEnum.Morning);
    public static readonly DayTime Afternoon = new DayTime("Afternoon", InnerEnum.Afternoon);
    public static readonly DayTime Night = new DayTime("Night", InnerEnum.Night);

    private static readonly List<DayTime> valueList = new List<DayTime>();

    static DayTime()
    {
        valueList.Add(Morning);
        valueList.Add(Afternoon);
        valueList.Add(Night);
    }

    //the inner enum needs to be public for use in 'switch' blocks:
    public enum InnerEnum
    {
        Morning,
        Afternoon,
        Night
    }

    public readonly InnerEnum innerEnumValue;
    private readonly string nameValue;
    private readonly int ordinalValue;
    private static int nextOrdinal = 0;

    private string description;

    internal DayTime(string name, InnerEnum innerEnum)
    {
        this.description = name;

        nameValue = name;
        ordinalValue = nextOrdinal++;
        innerEnumValue = innerEnum;
    }

    public string Description
    {
        get
        {
            return description;
        }
    }

    //the following methods reproduce Java built-in enum functionality:

    public static DayTime[] values()
    {
        return valueList.ToArray();
    }

    public int ordinal()
    {
        return ordinalValue;
    }

    public override string ToString()
    {
        return nameValue;
    }

    public static DayTime valueOf(string name)
    {
        foreach (DayTime enumInstance in DayTime.valueList)
        {
            if (enumInstance.nameValue == name)
            {
                return enumInstance;
            }
        }
        throw new System.ArgumentException(name);
    }
}

鉴于这种复杂性,最好以对 C# 更自然的方式重写您的逻辑,而不使用枚举。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多