Concisely creating an IDictionary<_,obj>

后端 未结 7 1527
萌比男神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:47

    Here's another "solution" which is inspired from Brian's suggestion but it uses reflection so there is a time and safety cost.

    let unboxPair (pair:obj) =
        let ty = pair.GetType()
        let x = ty.GetProperty("Item1").GetValue(pair,null) :?> string
        let y = ty.GetProperty("Item2").GetValue(pair,null)
        x,y
    
    let unboxPairs (pairs:obj list) =
      pairs |> List.map unboxPair  
    
    let values =
      unboxPairs
        ["a", 1
         "b", "foo"
         "c", true]
      |> dict
    

提交回复
热议问题