简体   繁体   English

F#Literal / constant可以用字符串组成,但不能用int组成?

[英]F# Literal/constant can be composed with strings, but not int?

Why is this OK: 为什么这样可以:

let [<Literal>] hi = "hi"
let [<Literal>] bye = "bye"
let [<Literal>] shortMeeting = hi + bye

...but this is not? ......但这不是?

let [<Literal>] me = 1
let [<Literal>] you = 1
let [<Literal>] we = me + you

The third line gives the error: 第三行给出错误:

This is not a valid constant expression

What's up with that? 那是怎么回事?

So the spec / docs are a little unclear, but provide hints. 所以spec / docs有点不清楚,但提供了提示。

From the spec (for F# 3.0): 从规范(对于F#3.0):

A value that has the Literal attribute is subject to the following restrictions: 具有Literal属性的值受以下限制:

It may not be marked mutable or inline. 它可能没有标记为可变或内联。 It may not also have the ThreadStaticor ContextStatic attributes. 它可能也没有ThreadStaticor ContextStatic属性。 The righthand 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. 一个简单的常量表达式,除了(),本机整数文字,无符号本机整数文字,字节数组文字,BigInteger文字和用户定义的数字文字。

OR 要么

A reference to another literal 对另一个文字的引用

This seems to suggest that even the combination of strings isn't allowed. 这似乎暗示即使是字符串的组合也是不允许的。

The documentation states that this changed in F# 3.1: 文档说明这在F#3.1中发生了变化:

https://msdn.microsoft.com/en-us/library/dd233193.aspx https://msdn.microsoft.com/en-us/library/dd233193.aspx

As of F# 3.1, you can use the + sign to combine string literals. 从F#3.1开始,您可以使用+号组合字符串文字。 You can also use the bitwise or (|||) operator to combine enum flags. 您还可以使用按位或(|||)运算符来组合枚举标志。 For example, the following code is legal in F# 3.1: 例如,以下代码在F#3.1中是合法的:

Note that integer addition is not on that list 请注意,整数添加不在该列表中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM