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

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

    The set of values which can be used as a default value are the same as can be used for an attribute argument. The reason being that default values are encoded into metadata inside of the DefaultParameterValueAttribute.

    As to why it can't be determined at compile time. The set of values and expressions over such values allowed at compile time is listed in official C# language spec:

    C# 6.0 - Attribute parameter types:

    The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:

    • One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.
    • The type object.
    • The type System.Type.
    • An enum type.
      (provided it has public accessibility and the types in which it is nested (if any) also have public accessibility)
    • Single-dimensional arrays of the above types.

    The type TimeSpan does not fit into any of these lists and hence cannot be used as a constant.

提交回复
热议问题