好了,是时候学习实参、形参、泛型…哦耶我!!我知道如何使用显式类型,但不知道如何使此方法泛型并传递所选择的枚举。任何建议/"导师守则";太好了。
using System;
public class Program
{
enum FarmAnimals { Cow = 1, Chicken, Goat, Horse }
enum ForrestAnimals { Lion = 1, Tiger, Elephant, Panther, Monkey }
enum SeaAnimals{ Whale = 1, Shark, Eel, Tuna, Swordfish, Dolphin, Sealion }
public static void Main()
{
Test();
}
static void Test()
{
bool whatever = true;
bool ok;
int pick = 0;
foreach (FarmAnimals animals in Enum.GetValues(typeof(FarmAnimals)))
{
int id = Convert.ToInt32(animals);
String name = Enum.GetName(typeof(FarmAnimals), animals);
Console.WriteLine("{0} - {1}", id, name);
}
while (whatever == true)
{
Console.Write("Pick a number ");
String line = Console.ReadLine();
ok = int.TryParse(line, out pick);
if (ok)
{
int counter = Enum.GetValues(typeof(FarmAnimals)).Length;
if (pick < 1 || pick > counter)
{
Console.WriteLine("You have an invalid number! You used {0}.", pick);
}
else
{
FarmAnimals animals = (FarmAnimals)pick;
Console.WriteLine("Great! You picked: {0}", animals);
}
}
else
{
Console.WriteLine("Please pick a number.");
}
}
}
}
你的代码有无限循环。必须有退出条件
下面的代码删除无尽循环和使用泛型方法,你可以传递任何枚举给它
public static void Test<T>() where T : Enum
{
Type enumType = typeof(T);
foreach (T enumValue in Enum.GetValues(enumType))
Console.WriteLine("{0} - {1}", Convert.ToInt32(enumValue), Enum.GetName(enumType, enumValue));
while (true)
{
Console.Write("Pick a number ");
string line = Console.ReadLine();
int pick;
bool ok = int.TryParse(line, out pick);
if (ok)
{
if (pick < 1 || pick > Enum.GetValues(enumType).Length)
Console.WriteLine("You have an invalid number! You used {0}.", pick);
else
Console.WriteLine("Great! You picked: {0}", Enum.GetName(enumType, pick));
break;
}
Console.WriteLine("Please pick a number.");
}
}
然后,你可以像这样使用
Test<SeaAnimals>();
Test<ForrestAnimals>();