我可以在 C# 中分配这样的布尔值吗?

Can I assign a bool like this in C#?

只是一个简单的问题,

是线,

bool myBool = (theNumber > 0);

在 C# 中有效吗?

显然,如果 'theNumber' 大于零,myBool 是否为真?

快速回答:您的代码没有任何问题。

bool myBool = (theNumber > 0);

有效,如果 theNumber 大于零,myBool 将变为真。

请参考link:

https://msdn.microsoft.com/en-us/library/c8f5xwh7.aspx

这里的例子使用:

bool b = true;
int days = ...;
// Assign the result of a boolean expression to b.
b = (days % 2 == 0);

希望对您有所帮助!

是的,这是有效的 C#,当然前提是 theNumber 是一种可以与数字进行比较的数据类型。表达式 theNumber > 0 的计算结果为布尔值(truetheNumber 大于零时),并且可以分配给布尔变量。

您也不需要值周围的括号,但如果您认为代码更易读,您可能希望保留它们:

bool myBool = theNumber > 0;

更快地回答这两个问题:是