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

由于我是 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")

https://stackoverflow.com/questions/6643727/

相关文章:

oop - R : Use a different base field/corpus 中的运算符重

perl - reverse 不在列表上下文中隐式使用 $_,这是一个错误吗?

ruby-on-rails-3 - Rails 3 在不注销的情况下设计更新密码

objective-c - [pool release] 和 [pool drain] 有什么区别?

java - 从代数表达式创建二叉树

function - 为什么 Matlab 看不到我的函数?

ruby-on-rails - ruby rails : How can I add a css f

bash - .bashrc 在云端?

amazon-ec2 - 使用pscp自动接受rsa指纹

django - 将 Django 模型/表拆分为两个模型/表是否有性能优势?