Java |
Java 5 has enum type. But version below Java 5,
there is no enum type. You may use array or class to
work like an enum type in C#.
class Color
{
public static int Red = 1;
public static int Blue = 2;
public static int Green = 3;
}
class Shape
{
public void Fill(Color color) {
switch(color) {
case color.Red:
...
break;
case color.Blue:
...
break;
case color.Green:
...
break;
default:
break;
}
}
}
You may use class or array to
replace enum in C#
public class EnumTest {
public static void main(String[] args) {
String[] DAYS = {"Sunday","Monday","Tuesday",
"Wednesday","Thursday",
"Friday","Saturday"};
for(int i = 0; i < DAYS.length; i++){
System.out.println("Number "+i+
" of EnumTest.DAYS is "+DAYS[i]);
}
}
}
The output:
Number 0 of EnumTest.DAYS is Sunday
Number 1 of EnumTest.DAYS is Monday
Number 2 of EnumTest.DAYS is Tuesday
Number 3 of EnumTest.DAYS is Wednesday
Number 4 of EnumTest.DAYS is Thursday
Number 5 of EnumTest.DAYS is Friday
Number 6 of EnumTest.DAYS is Saturday
public class Direction {
public final static int NORTH = 1;
public final static int EAST = 2;
public final static int WEST = 3;
public final static int SOUTH = 4;
}
Usage:
int wall = Direction.NORTH;
|
|
C# |
An enum type is a user defined value type.
It is used for "multiple choice" scenarios.
It contains constants.
enum Color
{
Red,
Blue,
Green
}
class Shape
{
public void Fill(Color color) {
switch(color) {
case Color.Red:
...
break;
case Color.Blue:
...
break;
case Color.Green:
...
break;
default:
break;
}
}
}
using System;
public class EnumTest
{
public enum DAYS: byte {
Monday, Tuesday, Wednesday, Thursday,
Friday, Saturday, Sunday}
public static void Main()
{
Array dayArray = Enum.GetValues(typeof(EnumTest.DAYS));
foreach (DAYS day in dayArray)
Console.WriteLine("Number {1} of EnumTest.DAYS is {0}",
day, day.ToString("d"));
}
}
The output:
Number 0 of EnumTest.DAYS is Sunday
Number 1 of EnumTest.DAYS is Monday
Number 2 of EnumTest.DAYS is Tuesday
Number 3 of EnumTest.DAYS is Wednesday
Number 4 of EnumTest.DAYS is Thursday
Number 5 of EnumTest.DAYS is Friday
Number 6 of EnumTest.DAYS is Saturday
public enum Direction {
North,
East,
West,
South
};
Usage:
Direction wall = Direction.North;
|
|