如何在F#中定义类型成员常量?

编程入门 行业动态 更新时间:2024-10-24 10:18:36
本文介绍了如何在F#中定义类型成员常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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#中定义类型成员常量?

本文发布于:2023-07-30 15:18:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250575.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常量   定义   成员   类型   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!