2017-07-17 174 views
1

这就是我用来选择基于枚举类型的函数。会有一种方法,我没有切换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 
     } 
    } 
} 
} 
+1

你可以使用'将字符映射到方法(可能是'委托',如['Func '](https://msdn.microsoft.com/en-us/library/bb549151(v = vs.110).aspx )) – UnholySheep

+0

@UnholySheep我在看,看来,我只是要重新考虑使用'Dictionary'命令我的'Switch' – UpTide

+0

记住,'switch'是描述这种查找的一种合理的富有表现力的方式,而性能方面,编译器会将代码转换为基于字典的查找,如果你有足够的'case'语句使其成为一个有价值的实现。 –

回答

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); 
0

考虑:

//types: 
//0 - red hair 
//1 - blue hair 

你可以这样做:

static public int CalcMe(Phenotypes phenotype, int input) 
{ 
    return input * 10 + 2* (int)phenotype; 
} 
+0

我的问题是,如果我需要改变红色乘以7,但蓝色除以20?这似乎很难改变。 – UpTide

+0

如果您将来需要切换您的逻辑,那么除非您使用可以调用单一功能的类,否则切换是一种方式。 –

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); 
}