当与 return 语句一起使用时,BitWise OR (“|”) 意味着什么?
在 C#.NET 中,有人见过类似这样的方法中的 return 语句吗?
protected override Buttons GetButtonsToShow()
{
return Buttons.New | Buttons.Return | Buttons.Delete;
}
这个 BitWise 运算符“|”怎么样?在这里工作?这个声明的结果是什么?我知道 BitWise 运算符如何在 if ... else ... 语句等中工作,但我从未见过它以这种方式使用。
In C#.NET, has anyone ever seen a return statement inside a method that looks like this?
protected override Buttons GetButtonsToShow()
{
return Buttons.New | Buttons.Return | Buttons.Delete;
}
How is this BitWise operator "|" working here? What is the result of this statement? I know how the BitWise operators work in if ... else ... statements and such, but I've never seen it used this way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
按钮
是一个标志 枚举。这使得它可以位映射,您可以使用按位运算符来组合值。
在这种情况下,它将返回一个值,该值是组合所有三个选项的位图。
这篇博客文章有相当清晰的解释(尽管它使用
&
作为示例)。Buttons
is a flags enum.This makes it bit-mappable where you can use bitwise operators to combine values.
In this case it will returns a value that is a bitmap combining all of the three options.
This blog post has quite a clear explanation (though it uses
&
for the example).从逻辑上讲,此类方法返回一组标志(枚举用
Flags
属性标记)。稍后您可以使用按位&
检查是否设置了某个标志。在这个特定的示例中,某处有代码检查是否显示某个按钮。像这样的东西:
Logically such methods return set of flags (the enum is marked with
Flags
attribute). Later you can check whether a certain flag is set using bitwise&
.In this particular example, somewhere there is code that checks whether to show a certain button. Something like this:
如果你分解这个表达,它就会变得更清楚:
你现在能看到它吗?
运营商 |不改变 return 语句本身。
Buttons.New | 的结果按钮。返回 | Buttons.Delete
表达式由函数返回。If you break down this expression it will become more clear:
Can you see it now?
The operator | does not alter the return statement itself. The result of the
Buttons.New | Buttons.Return | Buttons.Delete
expression is returned by the function.它执行按位运算并将结果作为返回值。 Buttons 是一个枚举,它应用了 FlagsAttribute 并看起来 :
GetButtonsToShow() 方法的返回值的用法如下
It is performing the bitwise operations and using the result as the return value. Buttons is an enumeration that has the FlagsAttribute applied to it and looks something like the following:
The usage of the return value from your GetButtonsToShow() method would be something like this: