可能重复:
按位或 | 是什么?运营商呢?
new Font(textBox1.Font, FontStyle.Bold | FontStyle.Italic);
接受此构造函数调用的方法签名是什么样的?
我从来不知道我可以使用“|” 方法调用中的运算符。我想了解更多。
'|'的英文单词是什么 操作员?(我什至不知道如何用谷歌搜索,因为我不知道用什么词来描述它)
在方法中使用它时,我如何向其他开发人员解释它?
你会建议我把这个运算符包含在我的技巧包中吗?
运营商有什么特别的注意事项吗?
可能重复:
按位或 | 是什么?运营商呢?
new Font(textBox1.Font, FontStyle.Bold | FontStyle.Italic);
接受此构造函数调用的方法签名是什么样的?
我从来不知道我可以使用“|” 方法调用中的运算符。我想了解更多。
'|'的英文单词是什么 操作员?(我什至不知道如何用谷歌搜索,因为我不知道用什么词来描述它)
在方法中使用它时,我如何向其他开发人员解释它?
你会建议我把这个运算符包含在我的技巧包中吗?
运营商有什么特别的注意事项吗?
接受方法的签名看起来像:
public Font(Font prototype, FontStyle newStyle)
{
...
}
此上下文中的|运算符(按位或)表示字体应为粗体和斜体。它的工作原理是这样的,因为它FontStyle是一个enum装饰有FlagsAttribute. FontStyle定义是:
[Flags]
public enum FontStyle
{
Bold = 1,
Italic = 2,
Regular = 0,
Strikeout = 8,
Underline = 4
}
因此,当您说 时FontStyle.Bold | FontStyle.Italic,它是按位或:
FontStyle.Bold = 1 = 00000001
FontStyle.Italic = 2 = 00000010
========
FontStyle.Bold | FontStyle.Italic = 3 = 00000011
稍后,您可以测试style参数以查看使用另一个位运算符 ( ) 设置了哪些位&。例如,如果您想查看上面生成的样式是否为粗体,您可以执行以下操作:
FontStyle myStyle = FontStyle.Bold | FontStyle.Italic;
bool isBold = (myStyle & FontStyle.Bold) == FontStyle.Bold;
例如,类Bold上的属性使用与上面几乎相同的代码Font检查是否是您给它的样式的一部分:FontStyle.Bold
public bool Bold
{
get
{
return ((this.Style & FontStyle.Bold) != FontStyle.Regular);
}
}
请注意,从 .NET Framework 4 开始,您可以使用它Enum.HasFlag()来测试标志的存在。例如,上面的属性定义可以简化为(使用 C# 6 中的一点语法糖):
public bool Bold => this.Style.HasFlag(FontStyle.Bold);