F#如何返回值为元组或null

F#如何返回值为元组或null,f#,F#,F#不允许返回null 如何让值以元组或null的形式返回?并不是F#不允许返回null 这是因为零件和其他零件有不同的类型 你可以用 使用retVal时,使用模式匹配: let retVal = if reader.Read() then Some (reader.GetString(0), getBytesData reader 1, reader.GetDateTime(2)) else None 为了给尹朱的答案添加一些额外的信息,F#语言中null值的情况如下

F#不允许返回null

如何让值以元组或null的形式返回?

并不是F#不允许返回null

这是因为零件和其他零件有不同的类型

你可以用

使用
retVal
时,使用模式匹配:

let retVal =
  if reader.Read() then
    Some (reader.GetString(0), getBytesData reader 1, reader.GetDateTime(2))
  else
    None

为了给尹朱的答案添加一些额外的信息,F#语言中
null
值的情况如下:

  • F#类型,如元组(例如,
    int*int
    ),这正是您的情况,没有
    null
    作为有效值,因此在这种情况下不能使用
    null
    (其他此类类型是函数值,例如
    int->int
    ,列表和大多数F#库类型)

  • .NET framework中的类型可以具有
    null
    值,因此您可以编写以下示例:

    match retVal with
    | Some v -> ...
    | None -> // null case
    
    这不是惯用的F#风格,但它是允许的

  • 如果您定义自己的F#类型,它将不会自动允许您使用
    null
    作为该类型的有效值(其目标是尽量减少在F#中使用
    null
    )。但是,您可以明确允许:

    let (rnd:Random) = null
    
    []
    类型MyType=。。。
    

为了进一步澄清,我复制了我的答案,该答案作为该问题的副本关闭:

如果需要它与C#进行互操作,可以使用
Unchecked.Defaultof
如下:

[<AllowNullLiteral>]
type MyType = ...
[<AllowNullLiteral>]
type MyType = ...
let retVal =
  if reader.Read() then
    (reader.GetString(0), getBytesData reader 1, reader.GetDateTime(2))
  else
    Unchecked.Defaultof<_>
let retVal =
  if reader.Read() then
    Some (reader.GetString(0), getBytesData reader 1, reader.GetDateTime(2))
  else
    None