5

我有一个event返回一个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
    (...)
}
4

4 回答 4

12

你可以使用

if (isValid.GetValueOrDefault())

这将给出falseif isValidis null

或使用??运算符

if (isValid ?? false)

如果不是null,则返回左操作数的值,否则返回右操作数的值。所以基本上是

if (isValid != null ? isValid : false)
于 2017-06-13T09:38:04.520 回答
2

你可以使用这个:

if (isValid.HasValue && isValid.Value)
于 2017-06-13T09:41:22.353 回答
1

一种选择是测试是否isValid有值:

if (isValid.HasValue && (bool)isValid)

另一种选择是isValid在没有人收听您的事件时提供默认值。这可以使用空合并运算符来完成:

bool isValid = ValidateStuff?.Invoke() ?? true;   // assume it is valid when nobody listens
于 2017-06-13T09:39:54.103 回答
1

问题是,在Nullable bool?的情况下,您有三值逻辑: truefalse因此null您必须明确说明ifnull应该被视为true,例如:

   if (isValid != false)     // either true or null
     GoToNextStep?.Invoke();

null应被视为false

   if (isValid == true)      // only true
     GoToNextStep?.Invoke(); 
于 2017-06-13T09:54:52.107 回答