f# - 将字典键添加到 F# 中的构造函数

标签 f# dictionary

由于我是 F# 的新手,这看起来像是某种基本问题。但是这里开始了。我有一个带有使用以下代码的构造函数的类:

new () = { 
    _index = 0; _inputString = ""; 
    _tokens = new Dictionary<string, string>() {
        {"key", "value"}
    }
}

一切正常,除了 F# 似乎不允许我向字典中添加标记。我可以用一个新的 Dictionary<> 对象初始化它,但如果我尝试填充它,它会抛出一个错误。我也不能用 .Add 成员来做。我看过 F# 构造函数初始化字段值的示例,但是否没有办法执行其他代码?

最佳答案

因为 Dictionarya 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/

相关文章:

asynchronous - F#:在 SynchronizationContext 中同步启动异步

F# 测量单位,类型转换时不丢失测量类型

python - Python 字典(内置哈希表)是如何实现的?

java最佳实践初始化arraylist映射定义

c++ - 在老板层次结构中查找 "top"老板仅适用于某些测试用例

c++ - map : Bad Ptr even if the key was found

python - 在python中按值获取字典中具有相同值的键?

f# - 使用单例区分联合类型是否会对性能产生影响?

haskell - Monad 还可以测量副作用

C# 交互位置