let retVal =
if reader.Read() then
(reader.GetString(0), getBytesData reader 1, reader.GetDateTime(2))
else
null
F#不允许空退换F#如何返回值有一个元组或空
我怎么能有返回值作为一个元组或空?
let retVal =
if reader.Read() then
(reader.GetString(0), getBytesData reader 1, reader.GetDateTime(2))
else
null
F#不允许空退换F#如何返回值有一个元组或空
我怎么能有返回值作为一个元组或空?
这不是说F#不允许你返回null。
这是因为部分和其他部分有不同的类型。您可以使用Option type。
let retVal =
if reader.Read() then
Some (reader.GetString(0), getBytesData reader 1, reader.GetDateTime(2))
else
None
当您使用retVal
,您使用模式匹配:
match retVal with
| Some v -> ...
| None -> // null case
要添加一些额外的信息,以尹朱的答案,同在F#语言null
值的情况下:
F#类型,如元组(例如int * int
),这正是您的情况,没有null
作为因此在这种情况下您不能使用null
(其他类型是函数值,例如, int -> int
,列表和大部分的F#库类型)从.NET框架
类型可以有null
价值,这样你就可以,例如写:
let (rnd:Random) = null
这不是地道的F#风格,但这是允许的。
如果你定义自己的F#类型,它不会自动允许您使用null
的类型(如下目标,以尽量减少在F#中使用null
)的有效值。但是,您可以明确地允许:
[<AllowNullLiteral>]
type MyType = ...