[personal profile] finesoul

The problem is that you cannot write generic with "where T: System.Enum" or "where T: System.ValueType" .
Fortunately I've found a workaround. It works even better than i expected it would.


The bonus is an inderect call of .AllOf<T>(...). On the picture we see a call of non-generic AllOf( ...) which is forbidden because it's private method. And still there is no error . But hint clarifies the miracle. Visual studio converts behind the scene a call AllOf( ...) into AllOf<T>(...) which is really nice :).





  1. /// <summary>

  2. /// Checks wheither at least one of optional flags is set

  3. /// </summary>

  4. /// <param name="flagsWeHave">The flags we have.</param>

  5. /// <param name="flagsWeSearch">The flags we search for.</param>

  6. /// <returns> true, if at least one of the flags in bit representation of both values is matching </returns>

  7. private static bool AnyOf(this IConvertible flagsWeHave, IConvertible flagsWeSearch)

  8. {

  9.     return (flagsWeHave.ToInt32(CultureInfo.InvariantCulture)

  10.         & flagsWeSearch.ToInt32(CultureInfo.InvariantCulture)) > 0;

  11.  

  12. }

  13.  

  14. /// <summary>

  15. /// Checks wheither at least one of optional flags is set

  16. /// </summary>

  17. /// <param name="flagsWeHave">The flags we have.</param>

  18. /// <param name="flagsWeSearch">The flags we search for.</param>

  19. /// <returns> true, if at least one of the flags in bit representation of both values is matching </returns>

  20. public static bool AnyOf<T>(this T flagsWeHave, T flagsWeSearch) where T : IConvertible

  21. {

  22.     if (!typeof(T).IsEnum && typeof(T) != typeof(int))

  23.         throw new ArgumentOutOfRangeException("T can only be enum or int");

  24.     return AnyOf(flagsWeHave as IConvertible, flagsWeSearch as IConvertible);

  25.  

  26. }

  27.  

  28. /// <summary>

  29. /// Checks wheither at least one of optional flags is set

  30. /// </summary>

  31. /// <param name="flagsWeHave">The flags we have.</param>

  32. /// <param name="flagsWeSearch">The flags we search for.</param>

  33. /// <returns> true, if at least one of the flags in bit representation of both values is matching </returns>

  34. private static bool AnyOf(this Enum flagsWeHave, Enum flagsWeSearch)

  35. {

  36.     return AnyOf(flagsWeSearch as IConvertible, flagsWeSearch as IConvertible);

  37. }




Лютий 2022

Н П В С Ч П С
  12345
6789101112
13141516171819
202122232425 26
2728     

За стиль дякую

Створено з Dreamwidth Studios
Сторінка створена 2026-Лют-12, Четвер 17:51