问题
I have the following types
type StatusCode =
| OK = 200
| NoContent = 204
| MovedTemp = 301
| MovedPerm = 302
| SeeOther = 303
| NotModified = 304
| NotFound = 404
| ServerError = 500
[<Literal>]
let NoBodyAllowedStatusCodes = [StatusCode.NoContent; StatusCode.NotModified]
And I'm getting a compile-time error that says:
This is not a valid constant expression or custom attribute value
I can't really figure out what's wrong here.
回答1:
In F#, and .NET in general, lists cannot be literals (constant in C#/VB.NET). Only primitive values can, like string
, bool
, etc. The F# 3.0 specification has the guidelines on what can or cannot be a literal in section 10.2.2:
A value that has the Literal attribute is subject to the following restrictions:
- It may not be marked mutable or inline.
- It may not also have the ThreadStatic or ContextStatic attributes.
- The right-hand side expression must be a literal constant expression that is made up of either:
- A simple constant expression, with the exception of (), native integer literals, unsigned native integer literals, byte array literals, BigInteger literals, and user-defined numeric literals.
—OR—
- A reference to another literal.
Depending on what you are trying to do, you could make your list static if the let
binding is being used in a class. If it is in a module, I'd just remove the Literal
attribute since let bindings are immutable by default, anyway.
来源:https://stackoverflow.com/questions/29349152/cannot-create-list-literal-in-f