F# 中的模块值不会被初始化.为什么? [英] Module values in F# don't get initialized. Why?

查看:20
本文介绍了F# 中的模块值不会被初始化.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 F# 时出现了奇怪的行为.当我在模块中使用 let 绑定时,如果该值是从构造函数创建的,那么在外部使用时它是未初始化的.(我从 C# 中使用 ModuleName.s2 或 ModuleName.f() 使用它)

I got a strange behavior when I used F#. When I use let binding in a module, and if the value is created from a constructor, then it's uninitialized when used outside. (I used it from C# using ModuleName.s2 or ModuleName.f())

//in a module
let s1 = "1" //normal
let s2 = new String('i', 5) //null

let f () =
    s2.Equals("something") //Exception

这是正常行为吗?提前致谢.

Is this a normal behavior? Thanks in advance.

出于调试目的,我选择将其编译为可执行文件.这可能是其他人指出的问题.

For the purpose of debugging, I choose to compile it as an executable. This may be the problem as other people pointed out.

推荐答案

在 F# 库中,模块通过静态构造函数进行初始化,以确保在使用任何模块值之前进行初始化.相比之下,在 F# 可执行文件中,此初始化是在应用程序的入口点中执行的.这意味着如果另一个程序集引用了 F# 应用程序(无论另一个应用程序是用什么语言编写的),初始化代码都不会运行.

In an F# library, modules are initialized via static constructors which ensure that initialization occurs prior to any of the module's values being used. By contrast, in an F# executable, this initialization is performed in the application's entry point. This means that if another assembly references the F# application (regardless of the language the other application is written in), the initialization code won't be run.

更新

Brian 向我指出了这部分规范的,表明这是预期的行为.

Brian pointed me to this part of the spec, which indicates that this is the expected behavior.

看起来一种解决方法是提供一个明确的入口点,如下所示:

It looks like one workaround would be to provide an explicit entry point, like this:

[<EntryPoint>]
let main _ =
    0

然后,您可以从 C# 应用程序中调用此 main 方法,以确保正确初始化模块的内容.

更新 2

我误读了规范 - 您实际上不需要从引用程序集中调用显式入口点.它的存在将导致初始化正确发生.

I was misreading the spec - you do not need to actually call the explicit entry point from the referencing assembly. Its mere presence will cause the initialization to occur correctly.

这篇关于F# 中的模块值不会被初始化.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆