Noc*_*ceo 1 c# events boolean winforms null-conditional-operator
我有一个event返回一个boolean.为了确保只有在有人监听的情况下才触发事件,我使用空条件运算符(questionmark)来调用它.但是,这意味着我必须将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
(...)
}
Run Code Online (Sandbox Code Playgroud)
你可以用
if (isValid.GetValueOrDefault())
Run Code Online (Sandbox Code Playgroud)
这将给false如果isValid是null.
或使用??运营商
if (isValid ?? false)
Run Code Online (Sandbox Code Playgroud)
如果不操作则返回左操作数null的值,否则返回右操作数的值.所以基本上是速记
if (isValid == null ? isValid : false)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2053 次 |
| 最近记录: |