flags

Most common C# bitwise operations on enums

假装没事ソ 提交于 2019-11-26 03:20:01
问题 For the life of me, I can\'t remember how to set, delete, toggle or test a bit in a bitfield. Either I\'m unsure or I mix them up because I rarely need these. So a \"bit-cheat-sheet\" would be nice to have. For example: flags = flags | FlagsEnum.Bit4; // Set bit 4. or if ((flags & FlagsEnum.Bit4)) == FlagsEnum.Bit4) // Is there a less verbose way? Can you give examples of all the other common operations, preferably in C# syntax using a [Flags] enum? 回答1: I did some more work on these

Anyone know a good workaround for the lack of an enum generic constraint?

北战南征 提交于 2019-11-26 00:20:37
问题 What I want to do is something like this: I have enums with combined flagged values. public static class EnumExtension { public static bool IsSet<T>( this T input, T matchTo ) where T:enum //the constraint I want that doesn\'t exist in C#3 { return (input & matchTo) != 0; } } So then I could do: MyEnum tester = MyEnum.FlagA | MyEnum.FlagB if( tester.IsSet( MyEnum.FlagA ) ) //act on flag a Unfortunately, C#\'s generic where constraints have no enum restriction, only class and struct. C# doesn\