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

Ice*_*ind 1 f# dictionary

就像我对F#的新手一样,这似乎是某种基本问题.但是这里.我有一个使用以下代码的构造函数的类:

new () = { 
    _index = 0; _inputString = ""; 
    _tokens = new Dictionary<string, string>() {
        {"key", "value"}
    }
}
Run Code Online (Sandbox Code Playgroud)

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

ild*_*arn 5

因为Dictionary一个构造函数接受一个IDictionary实例,你可以使用内置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")])
        }
Run Code Online (Sandbox Code Playgroud)

但是,也可以在构造函数的对象初始值设定项之前或之后执行非平凡的代码:

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")
Run Code Online (Sandbox Code Playgroud)


Tom*_*cek 5

Ildjarn已经回答了你的问题,但是我只想添加一个关于编码风格的注释 - 我认为现在大多数F#程序更喜欢隐式构造函数语法,你可以在其中定义一个隐式构造函数作为type声明的一部分.这通常使代码更简单.你可以这样写:

type Bah() = 
  let index = 0
  let inputString = ""
  let tokens = new Dictionary<string, string>()
  do tokens.Add("bazKey", "barValue")

  member x.Foo = "!"
Run Code Online (Sandbox Code Playgroud)

这定义了无参数构造函数和私有字段(例如index).在您的示例中,这没有多大意义(因为所有字段都是不可变的,所以index总是为零).我想你可能有其他的构造函数,在这种情况下你可以编写类似的东西:

type Baf(index:int, inputString:string, tokens:Dictionary<string, string>) =
  new() = 
    let tokens = new Dictionary<string, string>()
    tokens.Add("bazKey", "barValue")
    Baf(0, "", tokens)
Run Code Online (Sandbox Code Playgroud)

在这里,您将获得两个构造函数 - 一个参数少,一个带三个参数.您还可以将隐式构造函数设为私有,并仅公开更具体的情况:

type Baf private (index:int, inputString:string, tokens:Dictionary<string, string>) =
  // (...)
Run Code Online (Sandbox Code Playgroud)

作为旁注,我也将命名更改_indexindex,因为我不认为F#指南建议使用下划线(尽管,对于声明使用的字段可能有意义val)