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

前端 未结 8 2066
星月不相逢
星月不相逢 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

    This works fine:

    void Foo(TimeSpan span = default(TimeSpan))

    Note: default(TimeSpan) == TimeSpan.Zero

    0 讨论(0)
  • 2020-11-28 11:41

    My VB6 heritage makes me uneasy with the idea of considering "null value" and "missing value" to be equivalent. In most cases, it's probably fine, but you might have an unintended side effect, or you might swallow an exceptional condition (for example, if the source of span is a property or variable that should not be null, but is).

    I would therefore overload the method:

    void Foo()
    {
        Foo(TimeSpan.FromSeconds(2.0));
    }
    void Foo(TimeSpan span)
    {
        //...
    }
    
    0 讨论(0)
提交回复
热议问题