C# 使用font类时,这些符号(&;~|)是什么意思
我有以下代码C# 使用font类时,这些符号(&;~|)是什么意思,c#,C#,我有以下代码 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); 我知道那个代码,但我不知道这些符号是什么意思&、|和~。 这些是平均值(and,or,not)还是
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);
我知道那个代码,但我不知道这些符号是什么意思&、|和~。这些是平均值(and,or,not)还是我错了?你是对的,它们是逻辑位运算符
new Font(oldf, oldf.Style & ~FontStyle.Bold);
具有从整体样式中删除粗体属性的效果(在我开始的时候,这些属性似乎总是有点落后,必须要做一些事情来摆脱它,但你会习惯的)
ORing会将粗体枚举添加到样式中
读一点书,然后用一张纸算出发生了什么,这很聪明,这种编码到处都在使用。是的
请查看这些链接以获取说明
它们是逻辑位运算符
new Font(oldf, oldf.Style & ~FontStyle.Bold);
这:
采用旧字体样式,通过对除(按位否定)粗体以外的每一位执行按位and来删除粗体
然而,这:
newf = new Font(oldf, oldf.Style | FontStyle.Bold);
正在设置由FontStyle.Bold表示的位。它们是按位操作<代码>是或
&
是和,而~
不是
您正在比较枚举的标志,因此其中的每一个(Style
,Bold
等)都是一个二次幂的数字。使用标志进行位操作的神奇之处在于,按位或两个标志将设置两个位。通过使用位掩蔽,有人可以找出哪些值是一起使用的,或者是否使用了特定的“枚举”
第一行要求字体的样式设置为true,而不是粗体
第二种是寻找具有样式
或粗体
的字体,它们是按位运算符:(行“逻辑(布尔和按位)”
基本上,它们在位级别上工作是和,|是或,~不是。下面是一个例子:
00000001b & 00000011b == 00000001b (any bits contained by both bytes)
00000001b | 00001000b == 00001001b (any bits contained in either byte)
~00000001b == 11111110b (toggle all bits)
我在这里使用单字节,但它也适用于多字节值。变量是位标志枚举。因此,您可以将它们与按位and运算符“$”一起进行and运算,或者将它们与按位or运算符“|”一起进行and运算
它们与枚举一起使用,因此允许您在下面的示例中指定多个选项
[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
}
正如其他人所说,它们是位运算符FontStyle
是一个位字段(一组标志)
这意味着“删除粗体”,但看看下面的数学,你会得到这样的结果
这意味着我们要加粗字体。通过使用exist值对其进行OR(这也意味着已经加粗的内容将保持加粗)
[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
}
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