简洁地创建一个 IDictionary<_ ,obj>;
是否有更短的方法来创建 IDictionary<_,obj>,可能不需要装箱每个值?这就是我所拥有的。
let values =
[ "a", box 1
"b", box "foo"
"c", box true ]
|> dict
Dictionary<_,obj>.Add
可以在不装箱的情况下调用,但我无法找到比我所拥有的更短的使用方法。
我希望除了定义拳击操作员之外还有其他东西。
编辑
根据布莱恩的建议,这是一种方法,但它有其自身的问题。
let values =
Seq.zip ["a"; "b"; "c"] ([1; "foo"; true] : obj list) |> dict
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
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.
EDIT
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是一个解决方案,遵循 kvb 的建议(可能是迄今为止最简洁、最清晰的):
Here's a solution, following kvb's suggestion (probably the most concise, and clearest, so far):
这是我能做的最巧妙的事情。它比你的拳击版本有更多的角色,但可能感觉不那么肮脏。请注意,
^
是右关联的(它是从 ocaml 继承的字符串连接运算符),这让它像::
一样工作,并且它比具有更强的优先级,
,这就是元组周围需要括号的原因。Here's the slickest thing I was able to whip up. It has more characters than your boxing version, but possibly feels a little less dirty. Note that the
^
is right-associative (it's the string concat operator inherited from ocaml), which lets it work like::
, and it has stronger precedence than,
, which is why the parenthesis are needed around the tuples.我在 FsSql 中遇到了类似的问题,我只是将拳击隐藏在函数中:
I had a similar problem in FsSql and I just tucked away boxing in a function:
这是另一个“解决方案”,其灵感来自 Brian 的建议,但它使用反射,因此存在时间和安全成本。
Here's another "solution" which is inspired from Brian's suggestion but it uses reflection so there is a time and safety cost.
斯蒂芬的想法的一个变体:
A variation of Stephen's idea:
还有另一种解决方案,只需在
Dictionary<'a,'b>
上定义一堆重载的扩展成员:当然,这里的
values
不是是不可变的就像你的问题一样,但我相信你可以在该目标中采用相同的策略。Yet another solution, simply define a bunch of overloaded extension members on
Dictionary<'a,'b>
:Of course
values
here is not immutable like in your question, but I'm sure you could employ the same strategy in that goal.一种方法是,列表文字左侧的类型签名将自动向上转换每个元素。
Is one way, the type signature on the left of the list literal will auto-upcast each element.