C# 三元运算符不工作

C# ternary operator not working

我有一个 class 的最小起订量模拟,我需要验证是否调用了某个方法。根据变量的类型,我需要检查该方法是否被调用过一次。

所以,这有效:

if (exception is ValidationException)
    mockRequestHandler.Verify(x => x.HandleException(exception), 
    Times.Once);
else
    mockRequestHandler.Verify(x => x.HandleException(exception), 
    Times.Never);

我正在尝试使用如下的三元运算符,但它似乎不起作用:

mockRequestHandler.Verify(x => x.HandleException(exception),
    (exception is ValidationException) ? Times.Once: Times.Never);

我收到以下编译时错误:

Type of conditional expression cannot be determined because there is no implicit conversion between 'method group' and 'method group'.

我是否忽略了一些简单的东西,或者不能以这种方式使用三元运算符?

正如我在this source file中看到的,Times.OnceTimes.Never实际上是静态方法,而不是属性。

为了验证方法被调用一次或从未被调用,您需要这样使用它:

mockRequestHandler.Verify(x => x.HandleException(exception), Times.Once());
mockRequestHandler.Verify(x => x.HandleException(exception), Times.Never());

因此,使用三元运算符将是:

mockRequestHandler.Verify(x => x.HandleException(exception), 
    (exception is ValidationException) ? Times.Once() : Times.Never());