Created
August 28, 2017 09:48
-
-
Save yagero/82fe597f83ef7a3287ae42c9ec753613 to your computer and use it in GitHub Desktop.
Enum.HasFlag in .NET 2 / Unity 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class UtilsEnum | |
{ | |
public static bool HasFlag(this Enum mask, Enum flags) // Same behavior than Enum.HasFlag is .NET 4 | |
{ | |
#if DEBUG | |
if (mask.GetType() != flags.GetType()) | |
throw new System.ArgumentException( | |
string.Format("The argument type, '{0}', is not the same as the enum type '{1}'.", | |
flags.GetType(), mask.GetType())); | |
#endif | |
return ((int)(IConvertible)mask & (int)(IConvertible)flags) == (int)(IConvertible)flags; | |
} | |
} | |
// UNIT TESTS | |
internal class TestUtilsEnum | |
{ | |
enum Flags | |
{ | |
Null = 0, | |
Motor = 1 << 1, | |
Wheels = 1 << 2, | |
Trunk = 1 << 3, | |
Bike = Wheels, | |
Motocross = Wheels | Motor, | |
Car = Motor | Wheels | Trunk, | |
} | |
enum Flags2 | |
{ | |
Null = 0, | |
Motor = 1 << 1, | |
} | |
[Test] | |
public void EnumHasFlag() | |
{ | |
Assert.IsTrue(Flags.Null.HasFlag(Flags.Null)); | |
Assert.IsFalse(Flags.Null.HasFlag(Flags.Motor)); | |
Assert.IsTrue(Flags.Car.HasFlag(Flags.Null)); | |
Assert.IsTrue(Flags.Car.HasFlag(Flags.Motor)); | |
Assert.IsTrue(Flags.Car.HasFlag(Flags.Trunk)); | |
Assert.IsTrue(Flags.Car.HasFlag(Flags.Motor | Flags.Wheels)); | |
Assert.IsTrue(Flags.Bike.HasFlag(Flags.Wheels)); | |
Assert.IsFalse(Flags.Bike.HasFlag(Flags.Motor)); | |
Assert.IsFalse(Flags.Bike.HasFlag(Flags.Wheels | Flags.Motor)); | |
Assert.IsFalse(Flags.Bike.HasFlag(Flags.Motor | Flags.Trunk)); | |
Assert.IsFalse(Flags.Wheels.HasFlag(Flags.Car)); | |
#if DEBUG | |
Assert.Throws<ArgumentException>(() => Flags.Car.HasFlag(Flags2.Motor)); | |
#endif | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment