You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

F#类型推断异常:无法设置.NET对象属性(FS0001错误)

问题解决:F#中设置SqlCommand属性的类型错误

错误原因

你使用的<|是F#的右向函数应用操作符,作用是将右侧参数传入左侧函数(比如f <| x等价于f x)。但cmd.Connection和cmd.CommandText是.NET属性而非函数,用<|会导致类型不匹配——编译器期望左侧是'a->'b类型的函数,实际却得到SqlConnection/string类型的值,因此触发FS0001错误。

修复方案

设置.NET对象属性需使用F#的赋值操作符<-,替换代码中的<|即可:

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

[<Literal>]
let ConnectionString = @"Data Source=(local);Initial Catalog=master;Integrated Security=True"

[<EntryPoint>]
let main argv =
    use conn = new SqlConnection(ConnectionString) // 用use自动释放连接资源
    conn.Open()
    let cmd = new SqlCommand()
    cmd.Connection <- conn
    cmd.CommandText <- "select getdate() as d"
    let da = new SqlDataAdapter(cmd)
    let ds = new DataSet()
    da.Fill ds |> ignore
    printfn "result is"
    0

更地道的F#写法

为简化代码,可直接通过构造函数传参或对象表达式初始化SqlCommand,避免分步赋值:

方式1:构造函数直接传参

let cmd = new SqlCommand("select getdate() as d", conn)

方式2:对象表达式初始化

let cmd = 
    SqlCommand(
        CommandText = "select getdate() as d",
        Connection = conn
    )

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 03:10:25