如何在c#中两个案例都为真的情况下获取枚举值

时间:2013-01-11 12:55:20

标签: c# enums

我有一个枚举,其中包含3个复选框的值:

public enum Str
{
    Test = 1,
    Exam = 2,
    Mark = 4
}

想象一下这些是复选框。如果我选择其中任何一个都可以正常工作但是当我选择多个复选框时,会添加枚举值。

当我检查测试和标记枚举值为5时,当我选择测试和检查时,结果为3 我甚至尝试过类型铸造

 string sVal = "checkbox Value";
 bool ival = int.TryParse(sValue,out iVal);
 if(iVal)
 {
   int iValue = int.Parse(sValue)
    str s = (str)iValue;
 }

再次“s”返回附加值而不是枚举类型如何解决这个问题?

5 个答案:

答案 0 :(得分:1)

我认为您正在寻找的是Flags属性:http://msdn.microsoft.com/en-gb/library/system.flagsattribute.aspx

答案 1 :(得分:1)

执行希望该值是1和4的加法。 以下是测试您的价值观的方法:

public enum Str
{
    Test = 1,
    Exam = 2,
    Mark = 4
}

private static void Main()
{
    Str test = (Str)5;  // Same as  test = Str.Test | Str.Mark;

    if ((test & Str.Test) == Str.Test)
    {
        Console.WriteLine("Test");
    }

    if ((test & Str.Exam) == Str.Exam)
    {
        Console.WriteLine("Exam");
    }

    if ((test & Str.Mark) == Str.Mark)
    {
        Console.WriteLine("Mark");
    }

    Console.Read();
}

应该使用Flag属性,因此其他人知道你的枚举应该用于按位操作。但是这个属性本身什么都不做(期望可能修改.ToString()结果)。

答案 2 :(得分:0)

您需要做几件事才能为您效劳。

  1. 在枚举上设置[Flags]属性。如果没有它,它将工作,但它是一件好事,即使仅用于文档目的。

    [Flags]
    public enum Str
    {
      None = 0
      Test = 1,
      Exam = 2,
      Mark = 4
    }
    
  2. 要设置枚举,您需要循环选中的复选框并设置值,如下所示:

    Str value = Str.None;
    if (chkTest.Checked)
       value = value | Str.Test;
    if (chkExam.Checked)
       value = value | Str.Exam;
    if (chkMark.Checked)
       value = value | Str.Mark;
    

    运行之后,如果检查测试和检查,则值为:

    (int) value       =>  3
    value.ToString()  => "Str.Test|Str.Exam".
    
  3. 要检查枚举值是否具有特定标志,您可以执行以下操作:

    Str value = ....
    if (value.HasFlag(Str.Test))
       // it has test selected 
    else
       // it does not have test selected
    

    或者你可以做到

    Str value = ....
    if (value & Str.Test == Str.Test)
       // it has test selected 
    else
       // it does not have test selected
    

答案 3 :(得分:0)

         if((EnumVal & Str.Exam) ==Str.Exam)|| EnumVal == Str.Exam) 

解决了.....

答案 4 :(得分:0)

您不能使用Flags属性。但是你的枚举值应该是2的幂。

您的枚举的值:

var values = Enum.GetValues(typeof(Str)).Cast<int>().Where(x => (x & iVal) != 0).ToList()

然后:

values.Select(x => list[(int)Math.Log(x, 2)])

list是您可以迭代并设置选中的复选框列表。

var list = new List<CheckBox>
           {
               firstCheckBox,
               secondCheckBox,
               thirdCheckBox,
           };