我可能以错误的方式使用枚举,但这是我的前提。我基本上有一组3个字符串,可以按任何顺序排列。而我想要做的就是选择符合此顺序的枚举。基本上我想知道哪些场景适用于进来的字符串。
我一直在研究测试应用程序,只是为了选择正确的Possibility
。也许下面的代码会更有意义。下面的foreach循环也可能不是最好的方法。在下面的代码中,您可以看到我{ "Cow", "Chicken", "Egg" };
我希望将其与枚举Scenario2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EnumEnumerables
{
class Program
{
enum Possibilitys
{
Scenario1 = Options.Chicken + Options.Cow + Options.Egg,
Scenario2 = Options.Cow + Options.Chicken + Options.Egg,
Scenario3 = Options.Egg + Options.Cow + Options.Chicken
}
enum Options
{
Chicken,
Cow,
Egg
}
static void Main(string[] args)
{
//this should result in scenario 1
//string[] myOrderofHistory = { "Chicken", "Cow", "Egg" };
//this should result in scenario 2
string[] myOrderofHistory = { "Cow", "Chicken", "Egg" };
foreach (string history in myOrderofHistory)
{
foreach (var value in Enum.GetValues(typeof(Possibilitys)))
{
if (value == history)
{
Console.WriteLine("{0,3} 0x{0:X8} {1}",
(int)value, ((Possibilitys)value));
}
}
}
}
}
}
答案 0 :(得分:1)
我绝不会建议使用这样的枚举,而是通过创建[Flags] Enum并使用左移位运算符<<你可以这样做:
class Program
{
[Flags]
enum Options
{
None = 0,
Chicken = 1,
Cow = 2,
Egg = 4,
}
enum Possibilities
{
Order1 = (Options.Chicken << 4) + (Options.Cow << 2) + Options.Egg,
Order2 = (Options.Cow << 4) + (Options.Chicken << 2) + Options.Egg,
Order3 = (Options.Egg << 4) + (Options.Cow << 2) + Options.Chicken,
}
static void Main(string[] args)
{
//this should result in scenario 1
//string[] myOrderofHistory = { "Chicken", "Cow", "Egg" };
//this should result in scenario 2
string[] myOrderofHistory = { "Cow", "Chicken", "Egg" };
int[] shiftValue = new int[] { 4, 2, 0 };
int shiftIndex = 0;
int possibility = 0;
foreach (string history in myOrderofHistory)
{
Options options = (Options)Enum.Parse(typeof(Options), history);
possibility += ((int)options) << shiftValue[shiftIndex];
shiftIndex++;
}
Console.WriteLine(((Possibilities)possibility).ToString());
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}