Java初学者:“|”背后的机制Shell 中的运算符 s = new Shell(d, SWT.CLOSE | SWT.RESIZE);
您好,我想知道下一个代码中“|
”运算符背后的机制。
Display d = new Display( );
Shell s = new Shell(d, SWT.CLOSE | SWT.RESIZE);
ps: 我已经查过源码了,但是没看懂
hi I was wondering about the mechanism behind the "|
" operator in the next code.
Display d = new Display( );
Shell s = new Shell(d, SWT.CLOSE | SWT.RESIZE);
p.s: I already checked the source code, but didn't understand
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
SWT.CLOSE
和SWT.RESIZE
是 int 标志。|
表示它们之间的Binary OR
,这意味着同时传递它们。例如。如果
RESIZE = 1(00000001 二进制)
和CLOSE = 2(00000010 二进制)
,SWT.CLOSE | SWT.RESIZE = 3(00000011 二进制)
稍后调用的方法将知道重新设置它们。编辑 - 下一步
如果构造函数根据标志进行行为,它可能看起来像这样:
现在,我们不再向构造函数传递许多不必要的参数,而是用一个参数(标志)告诉它许多事情做。例如,第一个
if
检查 flags 中是否设置了 CLOSE 标志:flags = 3 (00000011 binary)
(正如我们之前设置的那样)SWT.CLOSE = 2(00000010 二进制)
和flags & SWT.CLOSE = 3 & 2 = 00000010 二进制
,大于零且已设置。SWT.CLOSE
andSWT.RESIZE
are int flags. the|
meansBinary OR
between them which meant for passing both of them.For example. if
RESIZE = 1 (00000001 binary)
andCLOSE = 2 (00000010 binary)
,SWT.CLOSE | SWT.RESIZE = 3 (00000011 binary)
and later on the method called will know to respcet them both.Edit - what's next
If the constructor behaves according to the flags, it might look like this:
Now, instead of passing many unnecessary arguments to the constructor, we tell it with one argument (flags) many things to do. The first
if
for example, checks if the CLOSE flag is set in flags:flags = 3 (00000011 binary)
(as we set it before)SWT.CLOSE = 2 (00000010 binary)
andflags & SWT.CLOSE = 3 & 2 = 00000010 binary
which is bigger than zero and is set.这是按位或运算符。
使用正确的整数,它可以用来定义选项。如果您的整数(但不一定)在整数中设置唯一位,则可以在接受方法上使用它来选择选项。
示例:
001
=> 1 (HIGHLIGHT_FG
)010
=> 2 (HIGHLIGHT_BG
)100
=> 4 (BOLD
)对常量进行排序
BOLD | HIGHLIGHT_FG 将为
5
。但它也可以定义为
HIGHLIGHT_ALL
,其中011
=> 3.It's the bitwise OR operator.
Using correct integers it can be used to define options. If your integers are - but not necesseraly - set unique bits in an integer it can be used on the accepting method to select options.
Example:
001
=> 1 (HIGHLIGHT_FG
)010
=> 2 (HIGHLIGHT_BG
)100
=> 4 (BOLD
)So oring the constants
BOLD | HIGHLIGHT_FG
will be5
.But it can be defined also a
HIGHLIGHT_ALL
with011
=> 3.它是按位或运算符。在本例中,它用于位字段,即
SWT.CLOSE | SWT.RESIZE
在整数变量中设置两位。It's the bitwise or operator. In this case it is used for a bitfield, i.e.
SWT.CLOSE | SWT.RESIZE
sets two bits in an integer variable.你的问题到底是什么?
管道运算符是按位或运算。
一般来说,在编程时,它允许您将两个值位组合在一起。例如,
0001b | 0010b 产生 0011。
What is your question, exactly?
The pipe operator is a bit-wise inclusive OR operation.
In general when programming, it lets you OR two values bits together. For example,
0001b | 0010b yields 0011.