2012-04-16 49 views
3

我有以下代碼這是什麼意思這些符號(〜|)時,使用的字體類

Font oldf; 
Font newf; 

oldf = this.richText.SelectionFont; 

if (oldf.Bold) 
    newf = new Font(oldf, oldf.Style & ~FontStyle.Bold); 
else 
    newf = new Font(oldf, oldf.Style | FontStyle.Bold); 

我知道的代碼,但我不知道這是什麼意思這些符號&,|和〜。
是這些意思(和,或不,)或我​​錯了嗎?

回答

1

像其他人一樣,他們是位運算符。 FontStyle是一個位域(一組標誌)。


oldf.Style & ~FontStyle.Bold 

這意味着「去掉粗體」但看着下面的數學,你會得到這樣的事情

(a) FontStyle.Bold = 0b00000010; // just a guess, it doesn't really matter 
(b) oldf.Style  = 0b11100111; // random mix here 
// we want Bold "unset" 
(c) ~FontStyle.Bold = 0b11111101; 
=> (b) & (c)  = 0b11100101; // oldf without Bold 

new Font(oldf, oldf.Style | FontStyle.Bold) 

這意味着我們要加粗的字體。通過將其與現有值進行或運算(這也意味着已經是大膽的東西將保持大膽)。

(a) FontStyle.Bold = 0b00000010; // just a guess, it doesn't really matter 
(b) oldf.Style  = 0b11100000; // random mix here 
=> (b) | (c)  = 0b11100010; // oldf with Bold 
0

你是對的,他們是邏輯按位運算符。

new Font(oldf, oldf.Style & ~FontStyle.Bold); 

已經從你的整體風格去掉粗體屬性的效果(這些總是顯得有點倒退到我,當我開始了,不必有所爲擺脫它,但你會習慣它)。

new Font(oldf, oldf.Style | FontStyle.Bold); 

ORing將爲您的樣式添加粗體枚舉。

做一些閱讀,然後研究一下紙上發生了什麼,這是非常聰明的,這種編碼被用在所有的地方。

0

他們的邏輯位運算符。

此:

newf = new Font(oldf, oldf.Style & ~FontStyle.Bold); 

走的是老字號的風格,並通過執行的位與每一位EXCEPT(按位取反)大膽除去大膽。

然而這樣的:

newf = new Font(oldf, oldf.Style | FontStyle.Bold); 

是通過設置代表FontStyle.Bold位。

1

它們是按位運算。 |是OR &是AND,而~不是。

您正在比較枚舉的標誌,所以其中的每一個(Style,Bold等)都是一個冪數爲2的數字。使用諸如此類標誌的位操作的神奇之處在於,兩個標誌的按位「或」將具有兩個位。通過使用位掩碼,人們可以計算出您與哪些值進行了或運算,或者是否使用了特定的「枚舉」。

第一行是詢問字體Style設置爲true,那不是Bold。第二部分是StyleBold

0

這些都是按位運算符:http://msdn.microsoft.com/en-us/library/6a71f45d%28v=vs.71%29.aspx

基本上,他們對位水平的工作(行「邏輯(布爾和位)」)。 &是AND,|是OR,〜不是。這裏有一個例子:

00000001b & 00000011b == 00000001b (any bits contained by both bytes) 
00000001b | 00001000b == 00001001b (any bits contained in either byte) 
~00000001b == 11111110b (toggle all bits) 

我在這裏使用了單個字節,但它也適用於多字節值。

0

變量是位標記枚舉。因此,您可以將它們與位運算符「$」一起使用,或者將它們與位運算符「|」一起進行或運算。

它們與枚舉一起使用,因此允許您在下面指定多個選項示例。

[Flags] 
enum Numbers { 
    one = 1 // 001 
    two = 2 // 010 
    three = 4 // 100 
} 

var holder = Numbers.two | Numbers.one; //one | two == 011 

if ((holder & Numbers.one) == Numbers.one) { 
    //Hit 
} 

if ((holder & Numbers.two) == Numbers.two) { 
    //Hit 
} 

if ((holder & Numbers.three) == Numbers.three) { 
    //Not hit in this example 
}