这就是我用来选择基于枚举类型的函数。会有一种方法,我没有切换CalcMe
功能?使用基于枚举值的函数?
namespace ClassLibrary1
{
public class Playbox
{
//types:
//0 - red hair
//1 - blue hair
//defines function to input based on hairtype.
//red:
// input*10
//blue:
// input*12
public enum Phenotypes
{
red,
blue
}
static public int Red(int input)
{
return input*10;
}
static public int Blue(int input)
{
return input*12;
}
static public int CalcMe(Phenotypes phenotype, int input)
{
switch (phenotype)
{
case Phenotypes.red:
return Red(input);
case Phenotypes.blue:
return Blue(input);
default:
return 0;
}
}
public class MyObject
{
int something;
Phenotypes hairtype;
public MyObject()
{
Random randy = new Random();
this.hairtype = (Phenotypes)randy.Next(2); //random phenotype
this.something = CalcMe(hairtype, randy.Next(15)); //random something
}
}
}
}
你可以使用'将字符映射到方法(可能是'委托',如['Func'](https://msdn.microsoft.com/en-us/library/bb549151(v = vs.110).aspx )) –
UnholySheep
@UnholySheep我在看,看来,我只是要重新考虑使用'Dictionary'命令我的'Switch' – UpTide
记住,'switch'是描述这种查找的一种合理的富有表现力的方式,而性能方面,编译器会将代码转换为基于字典的查找,如果你有足够的'case'语句使其成为一个有价值的实现。 –