无法在F#中创建列表文字 [英] Cannot create list literal in F#

查看:99
本文介绍了无法在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]

我得到一个编译时错误,指出:

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.

推荐答案

在F#和.NET中,列表不能是文字(在C#/VB.NET中是常数).只有原始值可以,例如stringbool等.F#3.0规范在第10.2.2节中提供了有关可以为字面值或不能为字面值的准则:

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:

  • 它可能未标记为可变或内联.
  • 它可能还没有ThreadStatic或ContextStatic属性.
  • 右侧表达式必须是由以下任意一个组成的文字常量表达式:
  • 一个简单的常量表达式,但(),本机整数文字,无符号本机整数文字,字节数组文字,BigInteger文字和用户定义的数字文字除外.
  • 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.

—或—

  • 对另一个文字的引用.

根据要执行的操作,如果在类中使用let绑定,则可以使列表静态.如果在模块中,我将删除Literal属性,因为默认情况下,let绑定是不可变的.

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.

这篇关于无法在F#中创建列表文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆