处理F#中的空值

时间:2011-02-14 20:37:38

标签: .net f# return-value null

正如你所看到的大量问题所见,我真的越来越深入了解F#:)

另一个疑问接近我的学习路径:空值。考虑到由于.NET框架和F#(或框架中的任何其他语言)之间的紧密集成,如何处理它们?

为了简单起见,这里有一段代码:

let myfunc alist =
   try
      List.find (fun x -> true) alist
   with
      | :? KeyNotFoundException as ex -> (* should return null *)

如何在函数中返回null?
除非已识别,否则null关键字无效。(nil不一样) 而且,一般来说,处理null返回值时的最佳做法是什么?

1 个答案:

答案 0 :(得分:6)

我不太确定问题是什么。如果你完成了你的例子:

open System.Collections.Generic

let myfunc alist =
   try
      List.find (fun x -> true) alist
   with
      | :? KeyNotFoundException as ex -> null

您会发现它编译得很好,推断类型myfunc : 'a list -> 'a when 'a : null表示存储在您传入的列表中的类型必须具有null作为正确的值。当使用C#,VB.NET等中定义的类型时,F#完全能够处理空值。

但是,当您不与使用其他.NET语言编写的代码进行互操作时,典型的方法是返回'a option以指示值可能存在也可能不存在。然后,你的例子将成为:

let myfunc alist =
   try
      List.find (fun x -> true) alist
      |> Some
   with
      | :? KeyNotFoundException as ex -> None

将适用于包含任何类型的列表(即使是那些没有null作为正确值的列表)。当然,在这种情况下,您可以改为使用List.tryFind (fun _ -> true)

相关问题