C# 4.0: Can I use a TimeSpan as an optional parameter with a default value?

前端 未结 8 2120
星月不相逢
星月不相逢 2020-11-28 10:55

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         


        
8条回答
  •  悲哀的现实
    2020-11-28 11:40

    You can work around this very easily by changing your signature.

    void Foo(TimeSpan? span = null) {
    
       if (span == null) { span = TimeSpan.FromSeconds(2); }
    
       ...
    
    }
    

    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.

    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.

提交回复
热议问题