我有一个 event
返回 boolean
.为了确保只有在有人正在监听时才会触发事件,我使用空条件运算符(问号)来调用它。
但是,这意味着我还必须将空条件运算符添加到返回的 boolean 值中。这意味着我无法弄清楚如何在之后的 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())
这将给
false
如果 isValid
是 null
.或使用
??
运算符(operator)if (isValid ?? false)
如果不是
null
,则返回左操作数的值否则为右操作数的值。所以基本上是一个简写if (isValid != null ? isValid : false)
关于c# - if 语句中的空条件 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44517614/