如何根据条件使用管道添加多个枚举值?

时间:2013-12-02 05:43:21

标签: c# enums

我试图根据条件为变量添加多个枚举值。例如,我有这样的事情:

SharedAccessBlobPermissions t = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read;

如果用户在UI上选择了其他可用的枚举值,我想添加它们很好。但看起来我们只能在一行上写它而不能在以后添加多个值。

我知道如何实现这一目标?

[更新] 基于答案,这就是我写的

var t= new SharedAccessBlobPermissions();
        if (isAllowRead)
        {
            t = SharedAccessBlobPermissions.Read;
        }
        if (isAllowWrite)
        {
            t |= SharedAccessBlobPermissions.Write;
        }

3 个答案:

答案 0 :(得分:3)

如果已使用[Flags]属性声明SharedAccessBlobPermissions 你可以做一些设置arithemtics。如果最初

  SharedAccessBlobPermissions t = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read;

添加:

  // Add SharedAccessBlobPermissions.Delete and SharedAccessBlobPermissions.Clear 
  t |= SharedAccessBlobPermissions.Delete | SharedAccessBlobPermissions.Clear;

减法:

  // Remove SharedAccessBlobPermissions.Delete
  t = (t | SharedAccessBlobPermissions.Delete) ^ SharedAccessBlobPermissions.Delete;

答案 1 :(得分:1)

您可以通过使用当前值按位来为位掩码添加更多值:

t |= SharedAccessBlobPermissions.AnotherOption

答案 2 :(得分:0)

您需要使用Flags属性。 请参阅以下示例:

[Flags]
enum DaysOfWeek
{
   Sunday = 1,
   Monday = 2,
   Tuesday = 4,
   Wednesday = 8,
   Thursday = 16,
   Friday = 32,
   Saturday = 64
}

public void RunOnDays(DaysOfWeek days)
{
   bool isTuesdaySet = (days & DaysOfWeek.Tuesday) == DaysOfWeek.Tuesday;

   if (isTuesdaySet)
      //...
   // Do your work here..
}

public void CallMethodWithTuesdayAndThursday()
{
    this.RunOnDays(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);
}

我建议您阅读以下Thread

Here是另一个有用的答案