我在第一个模块中定义了一个空的可变字典let mutable.在后续模块(知道第一个模块)中,我尝试将一个键值对添加到字典中,但此代码从不运行(但编译成功).为什么?
另一方面,似乎字典可以在其定义的模块内成功变异.
File1.fs
module File1
let mutable dictionary = System.Collections.Generic.Dictionary<string, int>()
Run Code Online (Sandbox Code Playgroud)
File2.fs
module File2
File1.dictionary.Add("one",1)
Run Code Online (Sandbox Code Playgroud)
Program.fs
[<EntryPoint>]
let main argv =
printfn "%A" File1.dictionary.["one"]
0 // return an integer exit code
Run Code Online (Sandbox Code Playgroud)
收到错误:
mscorlib.dll中发生未处理的"System.Collections.Generic.KeyNotFoundException"类型的异常附加信息:字典中不存在给定的键.
你没有任何调用代码的东西File2.这样做的正确方法是在一个函数内,所以
File2.fs
module File2
let addOne() = File1.dictionary.Add("one", 1)
Run Code Online (Sandbox Code Playgroud)
Program.fs
let main _ =
File2.addOne()
printfn....
Run Code Online (Sandbox Code Playgroud)
也就是说,F#中通常避免全局可变状态; 拥有a File1.createDict(),然后将其File2.addOne作为参数传递,而不是将其存储为全局变量,这是更惯用的.
旁注你实际上并不需要mutable那里的标记,因为这意味着字典引用本身是可变的,而不仅仅是它的内容(它的定义总是可变的Dictionary).
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |