使用基于枚举值的函数?

UpT*_*ide 1 c# enums

这就是我用来根据枚举类型选择函数的方法。有没有我没有切换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
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

EZI*_*EZI 6

你可以使用这样的字典

Dictionary<Phenotypes, Func<int, int>> Mappings = new Dictionary<Phenotypes, Func<int, int>>()
{
    {Phenotypes.red, x=> Red(x) },
    {Phenotypes.blue, x=> Blue(x) }
};
Run Code Online (Sandbox Code Playgroud)

现在你可以这样称呼它

var something = Mappings[Phenotypes.blue](666);
Run Code Online (Sandbox Code Playgroud)