简体   繁体   English

Moq.Times 参数默认值? 如何创建结构常量,bc Moq.Times.Once() 不是编译时常量

[英]Moq.Times parameter default value? how to create a struct constant, bc Moq.Times.Once() is not a compile time constant

I have a parameter that is of type Moq.Times and I want it to have a default value of Moq.Times.Once() except Once() is a method and not a compile time constant.我有一个 Moq.Times 类型的参数,我希望它具有 Moq.Times.Once() 的默认值,但 Once() 是一种方法而不是编译时间常数。

So I set made the parameter nullable and set the default value to null and then in the method, if the param value is null, I set it to / invoke Moq.Times.Once() and that's fine, but what I'd really like to do is have a default value of Moq.Times.Once()因此,我将参数设置为可为空并将默认值设置为 null,然后在方法中,如果参数值为 null,我将其设置为/调用 Moq.Times.Once(),这很好,但我真的想要喜欢做的是有一个默认值 Moq.Times.Once()

Is there a more clever / simpler way to do this?有没有更聪明/更简单的方法来做到这一点?

What I want but doesn't compile:我想要但没有编译的东西:

void MyMethod(Moq.Times invocationTimes = Moq.Time.Once()) { ... }

What I do instead:我做的是:

void MyMethod(Moq.Times? invocationTimes = null) { if (invocationTimes == null) { invocationTimes = Times.Once(); }}

Yes, you should allow null and then replace that at runtime.是的,您应该允许null然后在运行时替换它。

You can make your code a bit more concise with the null coalescing operator since C# 8 : 自 C# 8 起,您可以使用 null 合并运算符使您的代码更加简洁

void MyMethod(Moq.Times? invocationTimes = null) 
{ 
    invocationTimes ??= Times.Once(); 
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM