1

以下代码SqlDataReadergetReaderIDataReader. 我究竟做错了什么?Seq.unfold

open System.Data
open System.Data.SqlClient
open System.Configuration

type Foo = { id:int; name:string }

let populateFoo (r:IDataReader) =
    let o = r.GetOrdinal
    { id = o "id" |> r.GetInt32; name = o "name" |> r.GetString; }

let iter populateObject (r:IDataReader)  =
    match r.Read() with
    | true -> Some(populateObject r, r)
    | _    -> None

let iterFoo = iter populateFoo

let getReader : IDataReader =
    let cnstr = ConfigurationManager.ConnectionStrings.["db"].ConnectionString
    let cn = new SqlConnection(cnstr)
    let cmd = new SqlCommand("select * from Foo", cn)
    cmd.ExecuteReader()

let foos = Seq.unfold iterFoo getReader
4

1 回答 1

3

F# 不会像 C# 那样自动向上转换,除非在某些特定情况下(请参阅规范,第 14.4.2 节)。

您必须显式转换表达式:cmd.ExecuteReader() :> IDataReader然后您可以在getReader.

或者,您可以让该函数SqlDataReader在调用站点返回一个和 upcast:

let foos = getReader :> IDataReader |> Seq.unfold iterFoo

如果unfold是具有这样签名的类型的静态成员:

type T() =
    static member unfold(a, b:IDataReader) = Seq.unfold a b

你可以直接做T.unfold(iterFoo, getReader),它会自动向上转换。这是规范中提到的情况之一。

于 2015-01-09T21:00:48.467 回答