C # vs Java Enum (per quelli nuovi a C#)


Ho programmato in Java per un po ' e sono stato lanciato su un progetto scritto interamente in C#. Sto cercando di aggiornarmi in c# e ho notato enumerazioni utilizzate in diversi punti del mio nuovo progetto, ma a prima vista le enumerazioni di c#sembrano più semplicistiche dell'implementazione Java 1.5+. Qualcuno può enumerare le differenze tra le enumerazioni c # e Java e come superare le differenze? (Non voglio iniziare una guerra di fiamma linguistica, voglio solo sapere come per fare alcune cose in C# che ho usato per fare in Java). Ad esempio, qualcuno potrebbe postare una controparte C # al famoso esempio di enum Planet di Sun?

public enum Planet {
  MERCURY (3.303e+23, 2.4397e6),
  VENUS   (4.869e+24, 6.0518e6),
  EARTH   (5.976e+24, 6.37814e6),
  MARS    (6.421e+23, 3.3972e6),
  JUPITER (1.9e+27,   7.1492e7),
  SATURN  (5.688e+26, 6.0268e7),
  URANUS  (8.686e+25, 2.5559e7),
  NEPTUNE (1.024e+26, 2.4746e7),
  PLUTO   (1.27e+22,  1.137e6);

  private final double mass;   // in kilograms
  private final double radius; // in meters
  Planet(double mass, double radius) {
      this.mass = mass;
      this.radius = radius;
  }
  public double mass()   { return mass; }
  public double radius() { return radius; }

  // universal gravitational constant  (m3 kg-1 s-2)
  public static final double G = 6.67300E-11;

  public double surfaceGravity() {
      return G * mass / (radius * radius);
  }
  public double surfaceWeight(double otherMass) {
      return otherMass * surfaceGravity();
  }
}

// Example usage (slight modification of Sun's example):
public static void main(String[] args) {
    Planet pEarth = Planet.EARTH;
    double earthRadius = pEarth.radius(); // Just threw it in to show usage

    // Argument passed in is earth Weight.  Calculate weight on each planet:
    double earthWeight = Double.parseDouble(args[0]);
    double mass = earthWeight/pEarth.surfaceGravity();
    for (Planet p : Planet.values())
       System.out.printf("Your weight on %s is %f%n",
                         p, p.surfaceWeight(mass));
}

// Example output:
$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
[etc ...]
Author: Ogre Psalm33, 2009-01-22

13 answers

Le enumerazioni nel CLR sono semplicemente chiamate costanti. Il tipo sottostante deve essere integrale. In Java un'enumerazione è più simile a un'istanza con nome di un tipo. Quel tipo può essere piuttosto complesso e - come mostra il tuo esempio-contiene più campi di vario tipo.

Per portare l'esempio in C# vorrei semplicemente cambiare l'enum in una classe immutabile ed esporre istanze statiche di sola lettura di quella classe:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Planet planetEarth = Planet.MERCURY;

            double earthRadius = pEarth.Radius; // Just threw it in to show usage
            double earthWeight = double.Parse("123");
            double earthMass   = earthWeight / pEarth.SurfaceGravity();

            foreach (Planet p in Planet.Values)
                Console.WriteLine($"Your weight on {p} is {p.SurfaceWeight(mass)}");

            Console.ReadKey();
        }
    }

    public class Planet
    {
        public static readonly Planet MERCURY = new Planet("Mercury", 3.303e+23, 2.4397e6);
        public static readonly Planet VENUS   = new Planet("Venus", 4.869e+24, 6.0518e6);
        public static readonly Planet EARTH   = new Planet("Earth", 5.976e+24, 6.37814e6);
        public static readonly Planet MARS    = new Planet("Mars", 6.421e+23, 3.3972e6);
        public static readonly Planet JUPITER = new Planet("Jupiter", 1.9e+27, 7.1492e7);
        public static readonly Planet SATURN  = new Planet("Saturn", 5.688e+26, 6.0268e7);
        public static readonly Planet URANUS  = new Planet("Uranus", 8.686e+25, 2.5559e7);
        public static readonly Planet NEPTUNE = new Planet("Neptune", 1.024e+26, 2.4746e7);
        public static readonly Planet PLUTO   = new Planet("Pluto", 1.27e+22, 1.137e6);

        public static IEnumerable<Planet> Values
        {
            get
            {
                yield return MERCURY;
                yield return VENUS;
                yield return EARTH;
                yield return MARS;
                yield return JUPITER;
                yield return SATURN;
                yield return URANUS;
                yield return NEPTUNE;
                yield return PLUTO;
            }
        }

        public string Name   { get; private set; }
        public double Mass   { get; private set; }
        public double Radius { get; private set; }

        Planet(string name, double mass, double radius) => 
            (Name, Mass, Radius) = (name, mass, radius);

        // Wniversal gravitational constant  (m3 kg-1 s-2)
        public const double G = 6.67300E-11;
        public double SurfaceGravity()            => G * mass / (radius * radius);
        public double SurfaceWeight(double other) => other * SurfaceGravity();
        public override string ToString()         => name;
    }
}
 217
Author: Kent Boogaart, 2018-06-20 20:26:50

In C# è possibile definire metodi di estensione sulle enumerazioni, e questo compensa alcune delle funzionalità mancanti.

È possibile definire Planet come enum e avere anche metodi di estensione equivalenti a surfaceGravity() e surfaceWeight().

Ho usato attributi personalizzati come suggerito da Mikhail, ma lo stesso potrebbe essere ottenuto usando un Dizionario.

using System;
using System.Reflection;

class PlanetAttr: Attribute
{
    internal PlanetAttr(double mass, double radius)
    {
        this.Mass = mass;
        this.Radius = radius;
    }
    public double Mass { get; private set; }
    public double Radius { get; private set; }
}

public static class Planets
{
    public static double GetSurfaceGravity(this Planet p)
    {
        PlanetAttr attr = GetAttr(p);
        return G * attr.Mass / (attr.Radius * attr.Radius);
    }

    public static double GetSurfaceWeight(this Planet p, double otherMass)
    {
        return otherMass * p.GetSurfaceGravity();
    }

    public const double G = 6.67300E-11;

    private static PlanetAttr GetAttr(Planet p)
    {
        return (PlanetAttr)Attribute.GetCustomAttribute(ForValue(p), typeof(PlanetAttr));
    }

    private static MemberInfo ForValue(Planet p)
    {
        return typeof(Planet).GetField(Enum.GetName(typeof(Planet), p));
    }

}

public enum Planet
{
    [PlanetAttr(3.303e+23, 2.4397e6)]  MERCURY,
    [PlanetAttr(4.869e+24, 6.0518e6)]  VENUS,
    [PlanetAttr(5.976e+24, 6.37814e6)] EARTH,
    [PlanetAttr(6.421e+23, 3.3972e6)]  MARS,
    [PlanetAttr(1.9e+27,   7.1492e7)]  JUPITER,
    [PlanetAttr(5.688e+26, 6.0268e7)]  SATURN,
    [PlanetAttr(8.686e+25, 2.5559e7)]  URANUS,
    [PlanetAttr(1.024e+26, 2.4746e7)]  NEPTUNE,
    [PlanetAttr(1.27e+22,  1.137e6)]   PLUTO
}
 223
Author: finnw, 2017-05-23 12:18:21

In C# gli attributi possono essere utilizzati con enumerazioni. Un buon esempio di questo modello di programmazione con descrizione dettagliata è qui (Codeproject)

public enum Planet
{
   [PlanetAttr(3.303e+23, 2.4397e6)]
   Mercury,
   [PlanetAttr(4.869e+24, 6.0518e6)]
   Venus
} 

Edit: questa domanda è stata recentemente posta di nuovo e risolta da Jon Skeet: Qual è l'equivalente dell'enum di Java in C#? Classi interne private in c# - perché non vengono utilizzate più spesso?

Modifica 2: vedi la risposta accettata{[3] } che estende questo approccio in modo molto brillante modo!

 37
Author: Mikhail, 2017-05-23 12:26:27

Le enumerazioni Java sono in realtà classi complete che possono avere un costruttore privato e metodi ecc., mentre le enumerazioni c# sono solo denominate numeri interi. L'implementazione di IMO Java è di gran lunga superiore.

Questa pagina dovrebbe aiutarti molto mentre impari c # proveniente da un campo java. (Il collegamento punta alle differenze sulle enumerazioni (scorri su / giù per altre cose)

 13
Author: Richard Walton, 2009-01-22 14:28:48

Qualcosa del genere penso:

public class Planets 
{
    public static readonly Planet MERCURY = new Planet(3.303e+23, 2.4397e6);
    public static readonly Planet VENUS = new Planet(4.869e+24, 6.0518e6);
    public static readonly Planet EARTH = new Planet(5.976e+24, 6.37814e6);
    public static readonly Planet MARS = new Planet(6.421e+23, 3.3972e6);
    public static readonly Planet JUPITER = new Planet(1.9e+27,   7.1492e7);
    public static readonly Planet SATURN = new Planet(5.688e+26, 6.0268e7);
    public static readonly Planet URANUS = new Planet(8.686e+25, 2.5559e7);
    public static readonly Planet NEPTUNE = new Planet(1.024e+26, 2.4746e7);
    public static readonly Planet PLUTO = new Planet(1.27e+22,  1.137e6);
}

public class Planet
{
    public double Mass {get;private set;}
    public double Radius {get;private set;}

    Planet(double mass, double radius)
    {
        Mass = mass;
        Radius = radius;
    }

    // universal gravitational constant  (m3 kg-1 s-2)
    private static readonly double G = 6.67300E-11;

    public double SurfaceGravity()
    {
        return G * Mass / (Radius * Radius);
    }

    public double SurfaceWeight(double otherMass)
    {
        return otherMass * SurfaceGravity();
    }
}

O combinare le costanti nella classe Planet come sopra

 4
Author: Chris S, 2016-11-29 16:12:30

Ecco un'altra idea interessante che si rivolge al comportamento personalizzato disponibile in Java. Mi è venuta in mente la seguente classe base Enumeration:

public abstract class Enumeration<T>
    where T : Enumeration<T>
{   
    protected static int nextOrdinal = 0;

    protected static readonly Dictionary<int, Enumeration<T>> byOrdinal = new Dictionary<int, Enumeration<T>>();
    protected static readonly Dictionary<string, Enumeration<T>> byName = new Dictionary<string, Enumeration<T>>();

    protected readonly string name;
    protected readonly int ordinal;

    protected Enumeration(string name)
        : this (name, nextOrdinal)
    {
    }

    protected Enumeration(string name, int ordinal)
    {
        this.name = name;
        this.ordinal = ordinal;
        nextOrdinal = ordinal + 1;
        byOrdinal.Add(ordinal, this);
        byName.Add(name, this);
    }

    public override string ToString()
    {
        return name;
    }

    public string Name 
    {
        get { return name; }
    }

    public static explicit operator int(Enumeration<T> obj)
    {
        return obj.ordinal;
    }

    public int Ordinal
    {
        get { return ordinal; }
    }
}

Ha un parametro di tipo fondamentalmente solo così il conteggio ordinale funzionerà correttamente tra diverse enumerazioni derivate. Esempio Operator di Jon Skeet dalla sua risposta a un'altra domanda (http://stackoverflow.com/questions/1376312/whats-the-equivalent-of-javas-enum-in-c) sopra quindi diventa:

public class Operator : Enumeration<Operator>
{
    public static readonly Operator Plus = new Operator("Plus", (x, y) => x + y);
    public static readonly Operator Minus =  new Operator("Minus", (x, y) => x - y);
    public static readonly Operator Times =  new Operator("Times", (x, y) => x * y);
    public static readonly Operator Divide = new Operator("Divide", (x, y) => x / y);

    private readonly Func<int, int, int> op;

    // Prevent other top-level types from instantiating
    private Operator(string name, Func<int, int, int> op)
        :base (name)
    {
        this.op = op;
    }

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

Questo dà alcuni vantaggio.

  • Supporto ordinale
  • Conversione in string e int che rende fattibili le istruzioni switch
  • GetType () darà lo stesso risultato per ciascuno dei valori di un tipo di enumerazione derivato.
  • I metodi statici di System.Enum possono essere aggiunti alla classe di enumerazione di base per consentire la stessa funzionalità.
 3
Author: Andrew Cooper, 2012-06-23 08:12:50

Abbiamo appena creato un'estensione enum per c# https://github.com/simonmau/enum_ext

È solo un'implementazione per typesafeenum, ma funziona alla grande, quindi abbiamo creato un pacchetto da condividere - divertiti con esso

public sealed class Weekday : TypeSafeNameEnum<Weekday, int>
{
    public static readonly Weekday Monday = new Weekday(1, "--Monday--");
    public static readonly Weekday Tuesday = new Weekday(2, "--Tuesday--");
    public static readonly Weekday Wednesday = new Weekday(3, "--Wednesday--");
    ....

    private Weekday(int id, string name) : base(id, name)
    {
    }
}
 3
Author: simonmau, 2019-08-07 14:38:42

Un enum Java è zucchero sintattico per presentare le enumerazioni in modo OO. Sono classi astratte che estendono la classe Enum in Java e ogni valore enum è come un'implementazione statica dell'istanza pubblica finale della classe enum. Guarda le classi generate e, per un enum "Foo" con 10 valori, vedrai le classi generate da "Foo 1 1" a "Foo classes 10".

Non conosco C# però, posso solo ipotizzare che un enum in quella lingua sia più simile a un enum tradizionale nei linguaggi di stile C. Mi vedi da una rapida ricerca su Google che possono contenere più valori, quindi sono probabilmente implementati in modo simile, ma con molte più restrizioni di quelle consentite dal compilatore Java.

 2
Author: JeeBee, 2009-01-22 14:27:15

Le enumerazioni Java consentono conversioni typesafe semplici dal nome utilizzando il metodo valueOf generato dal compilatore, ovvero

// Java Enum has generics smarts and allows this
Planet p = Planet.valueOf("MERCURY");

L'equivalente per un enum grezzo in c# è più dettagliato:

// C# enum - bit of hoop jumping required
Planet p = (Planet)Enum.Parse(typeof(Planet), "MERCURY");

Tuttavia, se si percorre il percorso sugegsted da Kent, è possibile implementare facilmente un metodo ValueOf nella classe enum.

 2
Author: serg10, 2009-04-08 08:56:46

Sospetto che le enumerazioni in c# siano solo costanti interne al CLR, ma non così familiari con esse. Ho decompilato alcune classi in Java e posso dirti che vuoi che le enumerazioni siano una volta convertite.

Java fa qualcosa di subdolo. Tratta la classe enum come una classe normale con, il più vicino possibile, usando molte macro quando si fa riferimento ai valori enum. Se si dispone di un'istruzione case in una classe Java che utilizza enum, sostituisce i riferimenti enum agli interi. Se hai bisogno di andare a stringa, crea una matrice di stringhe indicizzate da un ordinale che utilizza in ogni classe. Sospetto di risparmiare sulla boxe.

Se scarichi questo decompilatore vedrai come crea la sua classe e la integra. Piuttosto affascinante ad essere onesti. Non usavo la classe enum perché pensavo che fosse gonfio solo per una serie di costanti. Mi piace meglio del modo limitato in cui puoi usarli in c#.

Http://members.fortunecity.com/neshkov/dj.html -- Decompilatore Java

 2
Author: Paul Bruner, 2011-06-04 19:48:50

L'enum in Java è molto più complesso di C# enum e quindi più potente. Dal momento che è solo un altro zucchero sintattico in fase di compilazione, mi chiedo se valesse davvero la pena di aver incluso il linguaggio dato il suo utilizzo limitato nelle applicazioni della vita reale. A volte è più difficile tenere le cose fuori dalla lingua che rinunciare alla pressione di includere una caratteristica minore.

 0
Author: dmihailescu, 2011-01-19 21:01:52
//Review the sample enum below for a template on how to implement a JavaEnum.
//There is also an EnumSet implementation below.

public abstract class JavaEnum : IComparable {
    public static IEnumerable<JavaEnum> Values {
        get {
            throw new NotImplementedException("Enumeration missing");
        }
    }

    public readonly string Name;

    public JavaEnum(string name) {
        this.Name = name;
    }

    public override string ToString() {
        return base.ToString() + "." + Name.ToUpper();
    }

    public int CompareTo(object obj) {
        if(obj is JavaEnum) {
            return string.Compare(this.Name, ((JavaEnum)obj).Name);
        } else {
            throw new ArgumentException();
        }
    }


    //Dictionary values are of type SortedSet<T>
    private static Dictionary<Type, object> enumDictionary;
    public static SortedSet<T> RetrieveEnumValues<T>() where T : JavaEnum {
        if(enumDictionary == null) {
            enumDictionary = new Dictionary<Type, object>();
        }
        object enums;
        if(!enumDictionary.TryGetValue(typeof(T), out enums)) {
            enums = new SortedSet<T>();
            FieldInfo[] myFieldInfo = typeof(T).GetFields(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public);
            foreach(FieldInfo f in myFieldInfo) {
                if(f.FieldType == typeof(T)) {
                    ((SortedSet<T>)enums).Add((T)f.GetValue(null));
                }
            }
            enumDictionary.Add(typeof(T), enums);
        }
        return (SortedSet<T>)enums;
    }
}


//Sample JavaEnum
public class SampleEnum : JavaEnum {
    //Enum values
    public static readonly SampleEnum A = new SampleEnum("A", 1);
    public static readonly SampleEnum B = new SampleEnum("B", 2);
    public static readonly SampleEnum C = new SampleEnum("C", 3);

    //Variables or Properties common to all enums of this type
    public int int1;
    public static int int2 = 4;
    public static readonly int int3 = 9;

    //The Values property must be replaced with a call to JavaEnum.generateEnumValues<MyEnumType>() to generate an IEnumerable set.
    public static new IEnumerable<SampleEnum> Values {
        get {
            foreach(var e in JavaEnum.RetrieveEnumValues<SampleEnum>()) {
                yield return e;
            }
            //If this enum should compose several enums, add them here
            //foreach(var e in ChildSampleEnum.Values) {
            //    yield return e;
            //}
        }
    }

    public SampleEnum(string name, int int1)
        : base(name) {
        this.int1 = int1;
    }
}


public class EnumSet<T> : SortedSet<T> where T : JavaEnum {
    // Creates an enum set containing all of the elements in the specified element type.
    public static EnumSet<T> AllOf(IEnumerable<T> values) {
        EnumSet<T> returnSet = new EnumSet<T>();
        foreach(T item in values) {
            returnSet.Add(item);
        }
        return returnSet;
    }

    // Creates an enum set with the same element type as the specified enum set, initially containing all the elements of this type that are not contained in the specified set.
    public static EnumSet<T> ComplementOf(IEnumerable<T> values, EnumSet<T> set) {
        EnumSet<T> returnSet = new EnumSet<T>();
        foreach(T item in values) {
            if(!set.Contains(item)) {
                returnSet.Add(item);
            }
        }
        return returnSet;
    }

    // Creates an enum set initially containing all of the elements in the range defined by the two specified endpoints.
    public static EnumSet<T> Range(IEnumerable<T> values, T from, T to) {
        EnumSet<T> returnSet = new EnumSet<T>();
        if(from == to) {
            returnSet.Add(from);
            return returnSet;
        }
        bool isFrom = false;
        foreach(T item in values) {
            if(isFrom) {
                returnSet.Add(item);
                if(item == to) {
                    return returnSet;
                }
            } else if(item == from) {
                isFrom = true;
                returnSet.Add(item);
            }
        }
        throw new ArgumentException();
    }

    // Creates an enum set initially containing the specified element(s).
    public static EnumSet<T> Of(params T[] setItems) {
        EnumSet<T> returnSet = new EnumSet<T>();
        foreach(T item in setItems) {
            returnSet.Add(item);
        }
        return returnSet;
    }

    // Creates an empty enum set with the specified element type.
    public static EnumSet<T> NoneOf() {
        return new EnumSet<T>();
    }

    // Returns a copy of the set passed in.
    public static EnumSet<T> CopyOf(EnumSet<T> set) {
        EnumSet<T> returnSet = new EnumSet<T>();
        returnSet.Add(set);
        return returnSet;
    }

    // Adds a set to an existing set.
    public void Add(EnumSet<T> enumSet) {
        foreach(T item in enumSet) {
            this.Add(item);
        }
    }

    // Removes a set from an existing set.
    public void Remove(EnumSet<T> enumSet) {
        foreach(T item in enumSet) {
            this.Remove(item);
        }
    }
}
 0
Author: Jim, 2012-06-27 06:15:01

È inoltre possibile utilizzare una classe di utilità per ogni tipo di enum che contiene un'istanza con dati avanzati per ogni valore di enum.

public enum Planet
{
    MERCURY,
    VENUS
}

public class PlanetUtil
{
    private static readonly IDictionary<Planet, PlanetUtil> PLANETS = new Dictionary<Planet, PlanetUtil();

    static PlanetUtil()
    {
        PlanetUtil.PLANETS.Add(Planet.MERCURY, new PlanetUtil(3.303e+23, 2.4397e6));
        PlanetUtil.PLANETS.Add(Planet.VENUS, new PlanetUtil(4.869e+24, 6.0518e6));
    }

    public static PlanetUtil GetUtil(Planet planet)
    {
        return PlanetUtil.PLANETS[planet];
    }

    private readonly double radius;
    private readonly double mass;

    public PlanetUtil(double radius, double mass)
    {
        this.radius = radius;
        this.mass = mass;
    }

    // getter
}
 0
Author: djmj, 2015-08-28 23:41:56