List all bit names from a flag Enum

后端 未结 4 619
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 04:26

I\'m trying to make a helper method for listing the names of all bits set in an Enum value (for logging purposes). I want have a method that would return the list of all the

4条回答
  •  忘掉有多难
    2020-12-10 04:31

    What if just do something like this:

    public static IEnumerable MaskToList(Enum mask)
    {
     if (typeof(T).IsSubclassOf(typeof(Enum)) == false)
        throw new ArgumentException();
    
      List toreturn = new List(100);
    
      foreach(T curValueBit in Enum.GetValues(typeof (T)).Cast())
      {
        Enum bit = (curValueBit as Enum);  // The only difference is actually here, 
                                           //  use "as", instead of (Enum) cast
    
        if (mask.HasFlag(bit))
          toreturn.Add(curValueBit);
      }
    
      return toreturn;
    }
    

    As the as has not compile time check. Compiler here just "believes" you, hoping that you know what you're doing, so the compile time error not raised.

提交回复
热议问题