Cannot create list literal in F#

懵懂的女人 提交于 2019-12-12 12:02:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!