As a newcomer to C#, navigating through codebases that heavily utilize enums can be challenging, especially coming from a strong Java background. This article aims to demystify the differences between C# and Java enums, empowering you to bridge the gap and harness the full potential of C# enumerations.
To illustrate the practical application of C# enums and extension methods, let's delve into the iconic Planet enum example used in Sun's Java documentation.
<code class="csharp">using System; 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 } public static class Planets { public static double GetSurfaceGravity(this Planet p) { return G * GetMass(p) / (GetRadius(p) * GetRadius(p)); } public static double GetSurfaceWeight(this Planet p, double otherMass) { return otherMass * p.GetSurfaceGravity(); } public const double G = 6.67300E-11; private static double GetMass(Planet p) => GetAttr(p).Mass; private static double GetRadius(Planet p) => GetAttr(p).Radius; private static PlanetAttr GetAttr(Planet p) => (PlanetAttr)Attribute.GetCustomAttribute(ForValue(p), typeof(PlanetAttr)); private static MemberInfo ForValue(Planet p) => typeof(Planet).GetField(Enum.GetName(typeof(Planet), p)); }</code>
In this C# implementation:
By utilizing C#'s extension methods, you can extend the functionality of enums to address use cases previously handled by Java's more robust enum implementation. This allows for a smooth transition and effective coding in C#.
The above is the detailed content of How Do C# and Java Enums Differ?. For more information, please follow other related articles on the PHP Chinese website!