从枚举标志中获取所有设置的枚举名称

时间:2013-03-24 12:46:07

标签: c# enums flags

如何将返回枚举值转换为整数值?

我希望将_allVisibleDays枚举中设置的所有标志作为整数值,如下所示:

TuesdayWednesday已设置然后我想将这些名称转换为DayOfWeek枚举以获取整数值:

所以Tuesday会返回2Wednesday 3,而不是以下枚举的24

我在SO上找到了这个方法:

public IEnumerable<int> GetFlags()
{
   foreach (Enum value in Enum.GetValues(typeof(VisibleDayOfWeek)))
     if (_allVisibleDays.HasFlag(value))
       yield return (int) value;
}

但我不能让它只是为了将枚举(上面的值)转换为整数的简单示例...

private VisibleDayOfWeek _allVisibleDays;


        [Flags]
        enum VisibleDayOfWeek : int
        {
            None = 0,
            Monday = 1, 
            Tuesday = 2,
            Wednesday = 4,
            Thursday = 8,
            Friday = 16,
            Saturday = 32,
            Sunday = 64
        }

2 个答案:

答案 0 :(得分:2)

由于VisibleDayOfWeekFlags枚举,而DayOfWeek不是,{2}之间没有直接对应的翻译(例如,VisibleDayOfWeek.Friday是16,而DayOfWeek.Friday是5)。特别是因为这些只是一周中的几天,未来可能不会改变(我希望!)我认为这里最好的选择就是用支票写一个简单的实用方法:

public IEnumerable<DayOfWeek> ConvertFromVisible(VisibleDayOfWeek visibleDay)
{
    if ((visibleDay & VisibleDayOfWeek.Monday) == VisibleDayOfWeek.Monday)
        yield return DayOfWeek.Monday;

    if ((visibleDay & VisibleDayOfWeek.Tuesday) == VisibleDayOfWeek.Tuesday)
        yield return DayOfWeek.Tuesday;

    if ((visibleDay & VisibleDayOfWeek.Wednesday) == VisibleDayOfWeek.Wednesday)
        yield return DayOfWeek.Wednesday;

    if ((visibleDay & VisibleDayOfWeek.Thursday) == VisibleDayOfWeek.Thursday)
        yield return DayOfWeek.Thursday;

    if ((visibleDay & VisibleDayOfWeek.Friday) == VisibleDayOfWeek.Friday)
        yield return DayOfWeek.Friday;

    if ((visibleDay & VisibleDayOfWeek.Saturday) == VisibleDayOfWeek.Saturday)
        yield return DayOfWeek.Saturday;

    if ((visibleDay & VisibleDayOfWeek.Sunday) == VisibleDayOfWeek.Sunday)
        yield return DayOfWeek.Sunday;
}

这样做的好处是可以自动返回DayOfWeek枚举,而不是后面的整数。

此外,由于这会跳过反射,因此它应该更具性能并且更能抵抗价值变化(尽管我怀疑这种情况会发生)。

编辑:如果你想调整他们返回的订单(比如你想从周日开始到周六),你可以轻松改变上面的行的顺序。

答案 1 :(得分:1)

您可以遍历Enum数组并检查索引。

public int GetEnumIndex(VisibleDayOfWeek day, bool ToBeConvertedToDoW)
{
     var allValues = Enum.GetValues(typeof(VisibleDayOfWeek));
     for (int i = 0; i <  allValues.Length ; i++)
     {
         if ((VisibleDayOfWeek)allValues.GetValue(i) == day)
         {
             //if you plan to convert to a DayOfWeek, this will return the
             //index for the DoW enum
             if(ToBeConvertedToDoW)
                return (i % 7);
             else //else return the actual index from VisibleDayOfWeek enum
                return i;
         }
     }
     return -1;
 }