Creating a generic List <T> in F#

会有一股神秘感。 提交于 2019-12-30 08:18:10

问题


I am trying to create a standard .NET List<T> in F# like this:

module Csv

open System;

type Sheet () =
  let rows = new List<Object>()

but I get the following error:

No constructors are available for the type List<Object>
C:\…\Csv.fs: 6

What am I doing wrong?


回答1:


As a simpler alternative to what others suggest, you can use the type named ResizeArray<T>. This is a type alias for System.Collections.Generic.List<T> defined in the F# core libraries:

type Sheet () = 
  let rows = new ResizeArray<Object>() 

In the compiled code, ResizeArray<T> will be compiled down to System.Collections.Generic. List<T>, so if you use your library from C#, there will not be any difference.

You do not have to open System.Collections.Generic, which would hide the definition of the F# List<T> type (though this is not a big problem), and I think that ResizeArray is a more appropriate name for the data structure anyway.




回答2:


You need to open System.Collections.Generic, too - the List<_> type you're referencing is F#'s immutable list type (from the Microsoft.FSharp.Collections namespace, which is opened by default), which doesn't expose public constructors.




回答3:


The List<T> class is defined in the System.Collections.Generic namespace, so you need to add:

open System.Collections.Generic


来源:https://stackoverflow.com/questions/12010316/creating-a-generic-list-t-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!