if 语句中的空条件布尔值
Null-conditional boolean in if statement
我有一个 event
,其中 returns 一个 boolean
。为确保事件仅在有人收听时触发,我使用 null 条件运算符(问号)调用它。
但是,这意味着我还必须将 null 条件运算符添加到返回的布尔值中。这意味着我之后无法弄清楚如何在 if 语句中使用它。有人知道如何处理吗?
switch (someInt)
{
case 1:
// Validate if the form is filled correctly.
// The event returns true if that is the case.
bool? isValid = ValidateStuff?.Invoke();
if (isValid)
// If passed validation go to next step in form
GoToNextStep?.Invoke();
break;
// There are more cases, but you get the point
(...)
}
你可以使用
if (isValid.GetValueOrDefault())
如果 isValid
是 null
, 将得到 false
。
或使用??
运算符
if (isValid ?? false)
其中 returns 如果不是 null
则为左操作数的值,否则为右操作数的值。所以基本上 shorthand for
if (isValid != null ? isValid : false)
一个选项是测试 isValid
是否有一个值:
if (isValid.HasValue && (bool)isValid)
另一种选择是在没有人收听您的活动时为 isValid
提供默认值。这可以通过空合并运算符来完成:
bool isValid = ValidateStuff?.Invoke() ?? true; // assume it is valid when nobody listens
你可以使用这个:
if (isValid.HasValue && isValid.Value)
问题是,在 Nullable bool?
的情况下,您有 three-valued logic:true
、false
和 null
因此如果 null
应被视为 true
,则必须明确地 ,例如:
if (isValid != false) // either true or null
GoToNextStep?.Invoke();
或null
应被视为false
:
if (isValid == true) // only true
GoToNextStep?.Invoke();
我有一个 event
,其中 returns 一个 boolean
。为确保事件仅在有人收听时触发,我使用 null 条件运算符(问号)调用它。
但是,这意味着我还必须将 null 条件运算符添加到返回的布尔值中。这意味着我之后无法弄清楚如何在 if 语句中使用它。有人知道如何处理吗?
switch (someInt)
{
case 1:
// Validate if the form is filled correctly.
// The event returns true if that is the case.
bool? isValid = ValidateStuff?.Invoke();
if (isValid)
// If passed validation go to next step in form
GoToNextStep?.Invoke();
break;
// There are more cases, but you get the point
(...)
}
你可以使用
if (isValid.GetValueOrDefault())
如果 isValid
是 null
, 将得到 false
。
或使用??
运算符
if (isValid ?? false)
其中 returns 如果不是 null
则为左操作数的值,否则为右操作数的值。所以基本上 shorthand for
if (isValid != null ? isValid : false)
一个选项是测试 isValid
是否有一个值:
if (isValid.HasValue && (bool)isValid)
另一种选择是在没有人收听您的活动时为 isValid
提供默认值。这可以通过空合并运算符来完成:
bool isValid = ValidateStuff?.Invoke() ?? true; // assume it is valid when nobody listens
你可以使用这个:
if (isValid.HasValue && isValid.Value)
问题是,在 Nullable bool?
的情况下,您有 three-valued logic:true
、false
和 null
因此如果 null
应被视为 true
,则必须明确地 ,例如:
if (isValid != false) // either true or null
GoToNextStep?.Invoke();
或null
应被视为false
:
if (isValid == true) // only true
GoToNextStep?.Invoke();