获取所有包含标志
本文关键字:标志 包含 获取 | 更新日期: 2023-09-27 17:53:17
我有一个包含一些标志的变量,我想知道如何检查设置了哪些标志。
我的旗帜。
[Flags]
public enum Button{
//Can't have more than 30 flags
//If an enum is added or deleted need to change for loop in method AddButton
// Exit flags
Exit = 1 << 0,
Cancel = 1 << 1,
Abort = 1 << 2,
Close = 1 << 3,
//Proced flags
Accept = 1 << 4,
Ok = 1 << 5,
Submit = 1 << 6,
//Question flags
No = 1 << 7,
Yes = 1 << 8,
//Save and load
Save = 1 << 9,
SaveAll = 1 << 10,
SaveNew = 1 << 11,
Open = 1 << 12,
Load = 1 << 12
}
这里是我检查标志的地方
for (int i = 1; i <= 12; ++i) {
if((buttons & 1 << i) == 1 << i){
}
}
显然我不能用这种方法来检查标志。
为了明确,我想知道在按钮中设置了哪些标志。
更新:我不能使用enum1 . hasflag(),因为我在Unity中制作游戏,它使用Mono。显然Mono还不支持hasFlag
我从这篇文章中提取了这个,它非常有用。它展示了如何使用具有位移位和位信息的enum。
http://www.codeducky.org/ins-outs-c-enums/// this attribute isn't strictly necessary, but it provides
// useful metadata and greatly improves the ToString() representation
[Flags]
enum BookFlags
{
// most flags enums provide a named None or Default
// zero value to represent the empty set
Default = 0,
HardCover = 1,
InStock = HardCover << 1, // 2
HasEBook = InStock << 1, // 4
OnSale = HasEBook << 1, // 8
}
// we can create and test flag sets with bitwise operations
BookFlags flags = BookFlags.HardCover | BookFlags.InStock;
var text = flags.ToString(); // HardCover, InStock
var isInStock = (flags & BookFlags.InStock) == BookFlags.InStock; // true
// testing for a particular flag is also simplified by the HasFlag extension
var isInStock2 = flags.HasFlag(BookFlags.InStock); // true
编辑:如果你不能使用HasFlag,你可能想要这样的东西。
// i redefined your enum a bit
public enum Buttons
{
// Default
Default = 0,
// Exit flags
Exit = 1,
Cancel = Exit << 1,
Abort = Cancel << 1,
Close = Abort << 1,
//Proced flags
Accept = Close << 1,
Ok = Accept << 1,
Submit = Ok << 1,
//Question flags
No = Submit << 1,
Yes = No << 1,
//Save and load
Save = Yes << 1,
SaveAll = Save << 1,
SaveNew = SaveAll << 1,
Open = SaveNew << 1,
Load = Open << 1
}
然后你可以…
// here's checking a selection of buttons against the complete enum universe of values
var lastButton = Convert.ToInt32(Enum.GetValues(typeof(Buttons)).Cast<Buttons>().Max());
int enumCheck;
Buttons flags = Buttons.Ok | Buttons.SaveNew | Buttons.Load | Buttons.No | Buttons.Submit | Buttons.Exit;
for (int i = 0; Math.Pow(2, i) <= lastButton; i++)
{
enumCheck = (int)Math.Pow(2, i);
if ((flags & (Buttons)enumCheck) == (Buttons)enumCheck)
{
Debug.WriteLine(Enum.GetName(typeof(Buttons), enumCheck));
}
}
产生输出(注意顺序):
Exit
Ok
Submit
No
SaveNew
Load
将buttons
转换为int
。你可能想要确保你的循环从0
开始,否则你会错过一个检查。
for (int i = 0; i <= 12; ++i)
{
if (((int)buttons & 1 << i) == 1 << i)
{
}
}