简洁地创建一个 IDictionary<_,obj> [英] Concisely creating an IDictionary<_,obj>

查看:19
本文介绍了简洁地创建一个 IDictionary<_,obj>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种更短的方法来创建 IDictionary<_,obj>,可能不需要装箱每个值?这就是我所拥有的.

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

let values =
  [ "a", box 1
    "b", box "foo"
    "c", box true ]
  |> dict

Dictionary<_,obj>.Add 可以在不装箱的情况下调用,但我想不出比我拥有的更短的使用方法.

Dictionary<_,obj>.Add can be called without boxing, but I couldn't figure out a way to use it that's shorter than what I have.

除了定义装箱运算符之外,我还希望有其他东西.

I'm hoping for something other than defining a boxing operator.

根据 Brian 的建议,这里有一种方法可以做到,但它有其自身的问题.

Based on Brian's suggestion, here's one way to do it, but it has its own problems.

let values =
  Seq.zip ["a"; "b"; "c"] ([1; "foo"; true] : obj list) |> dict

推荐答案

这是一个解决方案,遵循 kvb 的建议(可能是迄今为止最简洁、最清晰的):

Here's a solution, following kvb's suggestion (probably the most concise, and clearest, so far):

let inline (=>) a b = a, box b

let values =
  [ "a" => 1
    "b" => "foo"
    "c" => true ]
  |> dict

这篇关于简洁地创建一个 IDictionary&lt;_,obj&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆