简体   繁体   English

F#:模块let和类型static let有什么区别?

[英]F#: What is the difference between module let and type static let?

Given the following: 给定以下内容:

module MyModule =
    let myObj = new MyObj()

type MyType() =
    static let myObj_ = new MyObj()
    static member myObj = myObj_

... are MyModule.myObj and MyType.myObj functionally (no pun intended) equivalent? ... MyModule.myObj和MyType.myObj在功能上(无双关)是等效的吗?

Whenever I call MyModule.myObj or MyType.myObj, I don't want the code to actually create a new object. 每当我调用MyModule.myObj或MyType.myObj时,我都不希望代码实际创建一个新对象。 I just want access to methods on a singleton object. 我只想访问单例对象上的方法。 I'm hoping that either of the above are suitable to that purpose. 我希望以上任何一种都适合该目的。

Try it and see? 试试看吧? I think these are the same, but I think you can author a MyObj type with a constructor that prints something and then easily verify the behavior with a short test program. 我认为这些是相同的,但是我认为您可以使用构造函数来编写MyObj类型,该构造函数将打印出一些内容,然后使用简短的测试程序轻松验证行为。 (Or maybe you're asking about something else I'm unclear about.) (或者您可能正在问其他我不清楚的问题。)

In both cases, the object is definitely only created once. 在这两种情况下,对象肯定只创建一次。

There is a small (theoretical) difference though. 但是,两者之间存在很小的(理论上的)差异。 With the static let, the object is only guaranteed to be created before MyType is used the first time ( MSDN ). 使用静态let,只能保证在第一次使用MyType( MSDN )之前创建对象。

A module-level let binding is probably executed at program startup (or maybe when a module is first used?). 模块级别的let绑定可能是在程序启动时执行的(或者也许是在第一次使用模块时?)。

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

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