c# - 使用基于枚举值的函数?

标签 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
        }
    }
}
}

最佳答案

你可以像这样使用字典

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

关于c# - 使用基于枚举值的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45154766/

相关文章:

java - isEnum() 匿名内部类的不明确行为

c# - app.config 从其他节点读取关键连接字符串的值

c# - Windows 8 开放桌面 IE10

c# - 与使用 Interlocked 类相比,使用 volatile 关键字有什么优势吗?

c# - 无法还原 ASP.NET Core 1.0 RTM 解决方案

java - 如何从字符串中获取枚举值?

c# - 如何避免使用枚举?

c# - 当我切换到不同的 XAML 时应用程序崩溃

c++ - 枚举成员的值可以自动递减而不是递增吗?

enums - 枚举 Elixir 数据(包括嵌套)并在 EEx 中显示键/值?