无法在 F# 中创建列表文字
Cannot create list literal in F#
我有以下类型
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]
我收到一个编译时错误:
This is not a valid constant expression or custom attribute value
我真的搞不懂这里出了什么问题。
在 F# 和一般的 .NET 中,列表不能是文字(在 C#/VB.NET 中为常量)。只有原始值可以,如 string
、bool
等。F# 3.0 规范在第 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.
根据您尝试执行的操作,如果 class 中使用了 let
绑定,您可以将列表设为静态。如果它在模块中,我将删除 Literal
属性,因为 let 绑定默认情况下是不可变的。
我有以下类型
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]
我收到一个编译时错误:
This is not a valid constant expression or custom attribute value
我真的搞不懂这里出了什么问题。
在 F# 和一般的 .NET 中,列表不能是文字(在 C#/VB.NET 中为常量)。只有原始值可以,如 string
、bool
等。F# 3.0 规范在第 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.
根据您尝试执行的操作,如果 class 中使用了 let
绑定,您可以将列表设为静态。如果它在模块中,我将删除 Literal
属性,因为 let 绑定默认情况下是不可变的。