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

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

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

    provided default(TimeSpan) is not a valid value for the function.

    Or

    //this works only for value types which TimeSpan is
    void Foo(TimeSpan span = new TimeSpan())
    {
        if (span == new TimeSpan()) 
            span = TimeSpan.FromSeconds(2); 
    }
    

    provided new TimeSpan() is not a valid value.

    Or

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

    This should be better considering chances of null value being a valid value for the function are rare.

提交回复
热议问题