[< Literal>]与F#中的其他常数有何不同 [英] how does [<Literal>] differ from other constants in F#
问题描述
我对Literal关键字以及为什么在F#中有必要感到困惑.
I am a bit confused by the Literal keyword and why it is necessary in F#.
在阅读文档时,听起来像[<Literal>]
用于定义常量,但是我有点困惑这个常量与F#中所有其他常量的区别.
Reading the docs, it sounds to me that [<Literal>]
is used to define a constant, however I am a bit confused how this constant differs from all other constants in F#..
旨在为常量的值可以用 文字属性.此属性的作用是使 被编译为常量.
Values that are intended to be constants can be marked with the Literal attribute. This attribute has the effect of causing a value to be compiled as a constant.
当我想到一个常数时,我想到的是不可变的....
When I think of a constant, I think of something which is immutable....
let x = "a" + "b" //this is a immutable value, its value is constant
[<Literal>]
let y = "a" + "b" //this is also a immutable value, but why is this a special constant?
是因为对正常" F#值的计算是惰性的,而对[<Literal>]
的计算却不是惰性的.是编译为常量"的意思.还是还有其他东西?
Is it because the 'normal' F# values are evaluated lazily and the [<Literal>]
is not evaluated lazily..? is that what they mean with 'compiled as constant'..? or is there something else to it?
推荐答案
在您的示例中,x
是在运行时分配的一个不可变值(但不是懒惰地求值),而y
是在编译时分配的.例如,
In your example, x
is an immutable value that is assigned during runtime (but NOT evaluated lazily), whereas y
is assigned during compiletime. As an example,
let myDLL = "foo.dll"
[<DllImport(myDLL, CallingConvention = CallingConvention.Cdecl)>]
extern void HelloWorld()
将不起作用,因为DllImport是一个属性,在编译过程中需要知道myDLL
的值.但是,这将起作用:
will not work, because DllImport is an attribute and needs to know the value of myDLL
during compilation. However, this will work:
[<Literal>]
let myDLL = "foo.dll"
[<DllImport(myDLL, CallingConvention = CallingConvention.Cdecl)>]
extern void HelloWorld()
这篇关于[< Literal>]与F#中的其他常数有何不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!