C# 是否使用基于枚举值的函数?
这就是我用来根据枚举类型选择函数的方法。是否有一种方法我没有切换CalcMe功能C# 是否使用基于枚举值的函数?,c#,enums,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
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
}
}
}
}
鉴于:
您可以这样做:
static public int CalcMe(Phenotypes phenotype, int input)
{
return input * 10 + 2* (int)phenotype;
}
鉴于:
您可以这样做:
static public int CalcMe(Phenotypes phenotype, int input)
{
return input * 10 + 2* (int)phenotype;
}
你可以用这样的字典
Dictionary<Phenotypes, Func<int, int>> Mappings = new Dictionary<Phenotypes, Func<int, int>>()
{
{Phenotypes.red, x=> Red(x) },
{Phenotypes.blue, x=> Blue(x) }
};
你可以用这样的字典
Dictionary<Phenotypes, Func<int, int>> Mappings = new Dictionary<Phenotypes, Func<int, int>>()
{
{Phenotypes.red, x=> Red(x) },
{Phenotypes.blue, x=> Blue(x) }
};
如果只是值乘法,则只需将整数值分配给这些枚举类型
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);
}
如果只是值乘法,则只需将整数值分配给这些枚举类型
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);
}
您可以使用一个字典将枚举映射到方法,可能是一个委托,例如@UnholySheep。我正在查看它,似乎我只是将我的开关替换为字典。请记住,开关是描述这种类型的查找的合理表达方式,而且性能方面,如果您有足够的case语句使其成为一个值得实现的程序,编译器将把代码转换为基于词典的查找。@PeterDuniho这是7355843的副本,应该关闭它。我认为您应该能够投票以副本的形式关闭您自己的问题。你试过了吗?你可以使用一个字典将枚举映射到方法,可能是一个委托,比如@UnholySheep,我正在看这个,似乎我只是想用字典替换我的开关。记住,开关是描述这种类型的查找的一种合理的表达方式,而且从性能上看,如果您有足够的case语句使其成为一个值得实现的程序,编译器将把代码转换为基于词典的查找。@PeterDuniho这是7355843的副本,应该关闭它。我认为您应该能够投票以副本的形式关闭您自己的问题。你试过了吗?我的问题是,如果我需要将红色改为乘以7,将蓝色改为除以20怎么办?这似乎很难改变。如果你将来需要切换逻辑,那么切换就是最好的选择,除非你使用可以调用单个函数的类。我的问题是,如果我需要将红色改为乘以7,将蓝色改为除以20怎么办?这似乎很难改变。如果您将来需要切换逻辑,那么除非您使用可以调用单个函数的类,否则切换就是最好的选择。