在C#中,可以这样定义类型成员常量:
In C# one can define a type member constant like this:
class Foo { public const int Bar = 600; }IL看起来像这样。
.field public static literal int32 Bar = int32(600)如何在Visual F#/ FSharp中执行相同的操作?
How can I do the same within Visual F# / FSharp?
我对此无济于事:
[<Sealed>] type Foo() = [<Literal>] let Bar = 600推荐答案
我用F#编译器做了一些实验,这是我的一些观察。如果要创建IL文字,则需要将标记为 Literal 的值放在模块内。像这样的例子:
I did a couple of experiments with the F# compiler and here are some my observations. If you want to create IL literal, then you need to place the value marked as a Literal inside a module. For example like this:
module Constants = [<Literal>] let Num = 1作为旁注,我对F#规范进行了快速搜索,似乎字面量可以对于模式匹配非常有用,因为您可以将它们用作模式(只要它们以大写字母开头):
As a side-note, I did a quick search through the F# specification and it seems that literals can be very useful for pattern matching, because you can use them as a pattern (as long as they start with an uppercase letter):
open Constants match 1 with | Num -> "1" | _ -> "other"现在,问题是,为什么文学放在类型声明中时,其行为与预期的不同。我认为原因是F#类型声明中的 let 声明不能是公共的,并且仅在类/类型内部可见。我相信,当您使用C#和F#时,它们都是内联文字值,而且这也是在类型声明中完成的。但是,由于文字不能公开,因此没有理由生成文字 IL字段,因为没有人可以访问它。
Now, the question is, why Literal doesn't behave as you would expect when you place it inside a type declaration. I think the reason is that let declaration inside an F# type declaration cannot be public and will be visible only inside the class/type. I believe that both C# and F# inline literal values when you use them and this is done inside type declarations too. However since the literal cannot be public, there is no reason for generating the literal IL field, because nobody could ever access it.
更多推荐
如何在F#中定义类型成员常量?
发布评论