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

查看:74
本文介绍了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天全站免登陆