问题描述
这两个都会产生一个错误,指出它们必须是编译时常量:
Both of these generate an error saying they must be a compile-time constant:
void Foo(TimeSpan span = TimeSpan.FromSeconds(2.0))
void Foo(TimeSpan span = new TimeSpan(2000))
首先,谁能解释一下为什么不能在编译时确定这些值?有没有办法为可选的 TimeSpan 对象指定默认值?
First of all, can someone explain why these values can't be determined at compile time? And is there a way to specify a default value for an optional TimeSpan object?
推荐答案
您可以通过更改签名轻松解决此问题.
You can work around this very easily by changing your signature.
void Foo(TimeSpan? span = null) {
if (span == null) { span = TimeSpan.FromSeconds(2); }
...
}
我应该详细说明 - 您示例中的那些表达式不是编译时常量的原因是因为在编译时,编译器不能简单地执行 TimeSpan.FromSeconds(2.0) 并将结果的字节粘贴到您的编译代码中.
I should elaborate - the reason those expressions in your example are not compile-time constants is because at compile time, the compiler can't simply execute TimeSpan.FromSeconds(2.0) and stick the bytes of the result into your compiled code.
例如,请考虑您是否尝试使用 DateTime.Now.DateTime.Now 的值在每次执行时都会改变.或者假设 TimeSpan.FromSeconds 考虑了重力.这是一个荒谬的例子,但编译时常量的规则不会仅仅因为我们碰巧知道 TimeSpan.FromSeconds 是确定性的而产生特殊情况.
As an example, consider if you tried to use DateTime.Now instead. The value of DateTime.Now changes every time it's executed. Or suppose that TimeSpan.FromSeconds took into account gravity. It's an absurd example but the rules of compile-time constants don't make special cases just because we happen to know that TimeSpan.FromSeconds is deterministic.
这篇关于C# 4.0:我可以使用 TimeSpan 作为具有默认值的可选参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!