簡體   English   中英

如何獲得按位組合的值

[英]How to get values of combined bitwise

我的類型具有從復選框中選擇的按位值 [1,2,4,8,16,32],當保存到數據庫時,我組合了選定的值並獲得了例如 42 的值。 我如何計算從組合值中選擇了哪些值,在編輯屏幕上我想重新檢查選擇的值。

要檢查例如 8 是否包含在您的組合值中,您可以使用按位和運算符,如下所示:

int combinedValue = 42;
int bitwiseValue = 8;
bool isBitwiseValueChecked = (combinedValue & bitwiseValue) == bitwiseValue;

使用enum對標志建模:

public static void Main()
{
    Console.WriteLine((MyFlags)1); // Foo
    Console.WriteLine((MyFlags)7); // Foo, Bar, Baz

    Console.WriteLine((int)(MyFlags.Foo | MyFlags.Bar)); // 3
}

[Flags]
enum MyFlags 
{
    Foo = 1,
    Bar = 2,
    Baz = 4
}

然后,要列出所有成員,請參閱List all bit names from a flag Enum

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM