由于我是 F# 的新手,这看起来像是某种基本问题。但是这里开始了。我有一个带有使用以下代码的构造函数的类:
new () = {
_index = 0; _inputString = "";
_tokens = new Dictionary<string, string>() {
{"key", "value"}
}
}
一切正常,除了 F# 似乎不允许我向字典中添加标记。我可以用一个新的 Dictionary<> 对象初始化它,但如果我尝试填充它,它会抛出一个错误。我也不能用 .Add 成员来做。我看过 F# 构造函数初始化字段值的示例,但是否没有办法执行其他代码?
最佳答案
因为 Dictionary
有 a constructor taking an IDictionary
instance ,您可以使用内置的 dict
函数在这里帮助你:
open System.Collections.Generic
type Foo =
val _index : int
val _inputString : string
val _tokens : Dictionary<string, string>
new () =
{
_index = 0
_inputString = ""
_tokens = Dictionary(dict [("fooKey", "fooValue")])
}
但是,也可以在构造函数的对象初始化器之前或之后执行重要代码:
type Bar =
val _index : int
val _inputString : string
val _tokens : Dictionary<string, string>
new () =
let tokens = Dictionary()
tokens.Add ("barKey", "barValue")
{
_index = 0
_inputString = ""
_tokens = tokens
}
type Baz =
val _index : int
val _inputString : string
val _tokens : Dictionary<string, string>
new () as this =
{
_index = 0
_inputString = ""
_tokens = Dictionary()
} then
this._tokens.Add ("bazKey", "bazValue")
关于f# - 将字典键添加到 F# 中的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6643727/