c#: what is a constant expression?

前端 未结 4 679
半阙折子戏
半阙折子戏 2021-01-18 11:30

I\'m working with attributes at the moment. I often run into the error \'An attribute argument must be a constant expression, typeof expression or array creation expression

4条回答
  •  伪装坚强ぢ
    2021-01-18 12:23

    Constant expressions are values determined solely at compile-time, including string concatenation of other constant expressions, arithmetic etc.

    So for example "" is a constant expression, but String.Empty isn't.

    String is the only reference type to support a non-null constant expression. For value types, the primitive types (int etc) and decimal support constant expressions... although you can't use decimal in attributes, as it's not a primitive in the CLR. (You can't even specify decimal as a parameter type in an attribute constructor.)

    See section 7.19 of the C# 4 spec for more information.

提交回复
热议问题