Concisely creating an IDictionary<_,obj>

后端 未结 7 1526
萌比男神i
萌比男神i 2020-12-03 23:09

Is there a shorter way of creating an IDictionary<_,obj>, possibly without boxing every value? This is what I have.

let values =
  [ \"a\"         


        
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 23:51

    A variation of Stephen's idea:

    open System
    open System.Collections.Generic
    
    type Dictionary<'a,'b> with
      member this.Add([] args:obj[]) =
        match args.Length with
        | n when n % 2 = 0 ->
          for i in 1..2..(n-1) do
            this.Add(unbox args.[i-1], unbox args.[i])
        | _ -> invalidArg "args" "even number of elements required"
    
    let d = Dictionary()
    d.Add(
      "a", 1,
      "b", "foo",
      "c", true
    )
    

提交回复
热议问题