F#集合初始化器语法 [英] F# collection initializer syntax

查看:68
本文介绍了F#集合初始化器语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

F#中的集合初始化器语法是什么?在C#中,您可以编写如下内容:

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

new Dictionary<string, int>() {
    {"One", 1},
    {"two", 2}}

我如何在F#中执行相同的操作?我想我可以采用自己的语法,但似乎应该已经有内置或标准的语法.

How do I do the same thing in F#? I suppose i could roll my own syntax, but seems like there should be a built-in or standard one already.

推荐答案

正如Jared所说,对于任意集合,对此没有内置支持.但是,C#代码只是Add方法调用的语法糖,因此您可以将其转换为:

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

如果想花哨的话,可以创建一个inline定义以进一步简化此过程:

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]

这篇关于F#集合初始化器语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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