c# - if 语句中的空条件 boolean 值

标签 c# winforms events boolean null-conditional-operator

我有一个 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如果 isValidnull .

或使用 ??运算符(operator)
if (isValid ?? false)

如果不是 null,则返回左操作数的值否则为右操作数的值。所以基本上是一个简写
if (isValid != null ? isValid : false)

关于c# - if 语句中的空条件 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44517614/

相关文章:

c# - 更好的方式来构建我在 View 字段上执行用户权限的方式

c# - 为什么在 ToDictionary 中使用 GroupBy 中的 key 时会收到 "key already added"错误?

c# - Blazor OnChange 事件

c# - 同时选中DataGridView中的所有复选框

python - sqlalchemy:获取受批量删除影响的行

c# - 按字母顺序对列表进行排序

c# - 如何在窗体中制作圆形标签?

c# - Winforms PropertyGrid 样式

vb.net - 处理表单中用户控件的控件事件

c# - 将事件处理程序附加到 Com 事件 : InvalidOperationException (S7-PLCSIM)