Java enums offer a powerful way to define constants with additional functionality, such as constructors, methods, and instance variables. While C# enums may seem simpler at first glance, they have drawbacks compared to Java's robust implementation.
Feature | Java | C# |
---|---|---|
Constructors | Supported | Not supported |
Methods | Supported | Requires extension methods |
Instance variables | Supported | Requires custom attributes or dictionaries |
Values | Immutable | Mutable |
Extension Methods: To add functionality similar to Java enums, C# allows defining extension methods on enums. For example, the following code provides methods to calculate surface gravity and surface weight:
<code class="csharp">public static class Planets { public static double GetSurfaceGravity(this Planet p) { /* ... */ } public static double GetSurfaceWeight(this Planet p, double otherMass) { /* ... */ } }</code>
Custom Attributes: Custom attributes can be used to store additional information on enums. Here is a sample implementation:
<code class="csharp">[PlanetAttr(3.303e+23, 2.4397e6)] public enum Planet { MERCURY, VENUS, EARTH, // ... } public class PlanetAttr : Attribute { public double Mass { get; private set; } public double Radius { get; private set; } public PlanetAttr(double mass, double radius) { Mass = mass; Radius = radius; } }</code>
By accessing the custom attribute on an enum value, you can retrieve the associated properties.
Here is a C# equivalent to Sun's Planet enum using extension methods and custom attributes:
<code class="csharp">public enum Planet { [PlanetAttr(3.303e+23, 2.4397e6)] MERCURY, [PlanetAttr(4.869e+24, 6.0518e6)] VENUS, [PlanetAttr(5.976e+24, 6.37814e6)] EARTH, // ... } public static class Planets { public const double G = 6.67300E-11; 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(); } private static PlanetAttr GetAttr(Planet p) { FieldInfo field = typeof(Planet).GetField(Enum.GetName(typeof(Planet), p)); return field.GetCustomAttribute<PlanetAttr>(); } }</code>
This code defines the Planet enum with custom attributes for mass and radius. The Planets class provides extension methods for calculating surface gravity and weight, which are accessible through the enums themselves.
The above is the detailed content of C# vs Java Enums: Which One Offers More Functionality?. For more information, please follow other related articles on the PHP Chinese website!