java 枚举一般用于,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 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;

}

}

2020-05-19

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值