如何在c#中两种情况都为true的情况下获取枚举值

本文关键字:true 情况下 获取 枚举 情况 两种 | 更新日期: 2023-09-27 17:52:44

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

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

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

当我选中Test and Mark Enum值为5时,当我选择Test and Exam时,结果为3我甚至试过打字

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

再次"s"返回的是添加值而不是枚举类型如何解决此问题?

如何在c#中两种情况都为true的情况下获取枚举值

确实希望该值是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()结果(。

我想您要找的是Flags属性:http://msdn.microsoft.com/en-gb/library/system.flagsattribute.aspx

您需要做几件事才能正常工作。

  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;
    

    运行后,如果检查了Test和exam,则值为:

    (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
    
         if((EnumVal & Str.Exam) ==Str.Exam)|| EnumVal == Str.Exam) 

已解决。。。。。

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

枚举的Int值:

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,
           };