这是我用来根据枚举类型选择功能的方法。会不会有我没有切换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
}
}
}
}
答案 0 :(得分:4)
您可以使用这样的词典
Dictionary<Phenotypes, Func<int, int>> Mappings = new Dictionary<Phenotypes, Func<int, int>>()
{
{Phenotypes.red, x=> Red(x) },
{Phenotypes.blue, x=> Blue(x) }
};
现在您可以将其称为
var something = Mappings[Phenotypes.blue](666);
答案 1 :(得分:0)
假设:
//types:
//0 - red hair
//1 - blue hair
你可以这样做:
static public int CalcMe(Phenotypes phenotype, int input)
{
return input * 10 + 2* (int)phenotype;
}
答案 2 :(得分:0)
如果它只是值乘法,则只需将整数值赋给那些枚举类型
public enum Phenotypes
{
red = 10,
blue = 12
}
然后您需要做的就是使用它们的整数值
Phenotypes[] phenoTypeArray = new Phenotypes[]{ red, blue};
public MyObject()
{
Random randy = new Random();
this.hairtype = phenoTypeArray[randy.Next(2)]; //random phenotype
this.something = (int)hairtype * randy.Next(15);
}