c#: what is a constant expression?

前端 未结 4 687
半阙折子戏
半阙折子戏 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:20

    The compiler needs to be able to create the Attributes at compile time, since they are embedded in your assembly with their actual data (they are instantiated by the compiler and serialized into the output file). That's why you need a constant expression.

    Basically you can use all the basic data types (like int, bool, string etc.). You can also use typeof expressions because they will be resolved to metadata tokens identifying a type, which is fine at compile time.

    Maybe you can put the concept of your Func into an interface that your types implement. Or into a separate handler class that you can pass to your Attribute by using a typeof(MyHandlerClass) expression.

提交回复
热议问题