栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

C#vs Java枚举(适用于C#新手)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#vs Java枚举(适用于C#新手)

CLR中的枚举简称为常量。基础类型必须是整数。在Java中,枚举更像是类型的命名实例。该类型可能非常复杂,并且-如您的示例所示-包含多个不同类型的字段。

要将示例移植到C#,我只需将枚举更改为不可变的类,并公开该类的静态只读实例:

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;    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465459.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号