F# collection initializer syntax

后端 未结 6 573
猫巷女王i
猫巷女王i 2021-02-03 19:05

What is the collection initializer syntax in F#? In C# you can write something like:

new Dictionary() {
    {\"One\", 1},
    {\"two\", 2}}
         


        
6条回答
  •  情话喂你
    2021-02-03 19:20

    As Jared says, there is no built-in support for this for arbitrary collections. However, the C# code is just syntactic sugar for Add method calls, so you could translate it to:

    let coll = MyCollectionType()
    ["One", 1; "Two", 2] |> Seq.iter coll.Add
    

    If you want to get fancy, you could create an inline definition to streamline this even further:

    let inline initCollection s =
      let coll = new ^t()
      Seq.iter (fun (k,v) -> (^t : (member Add : 'a * 'b -> unit) coll, k, v)) s
      coll
    
    let d:System.Collections.Generic.Dictionary<_,_> = initCollection ["One",1; "Two",2]
    

提交回复
热议问题