F#:Nullable <t>支持</t>

时间:2009-06-03 19:51:37

标签: f# null

在F#中使用Nullable的正确方法是什么?

目前我正在使用它,但它似乎非常混乱。

let test (left : Nullable<int>) = if left.HasValue then left.Value else 0

Console.WriteLine(test (new System.Nullable<int>()))
Console.WriteLine(test (new Nullable<int>(100)))

let x = 100
Console.WriteLine(test (new Nullable<int>(x)))

2 个答案:

答案 0 :(得分:21)

我担心F#中的可空类型没有语法糖(不像在C#中你只需要在类型中附加?)。所以是的,你在那里展示的代码确实看起来非常冗长,但它是在F#中使用System.Nullable<T>类型的唯一方法。

但是,我怀疑你真正想要使用的是option types。 MSDN页面上有一些不错的例子:

let keepIfPositive (a : int) = if a > 0 then Some(a) else None

open System.IO
let openFile filename =
   try
       let file = File.Open (filename, FileMode.Create)
       Some(file)
   with
       | exc -> eprintf "An exception occurred with message %s" exc.Message; None 

显然使用起来好多了!

选项基本上履行了F#中可空类型的角色,我认为你真的想要使用它们而不是可空类型(除非你正在使用C#进行互操作)。实现的不同之处在于选项类型由Some(x)None区分联合组成,而Nullable<T>是BCL中的普通类, C#中的一些语法糖。

答案 1 :(得分:16)

你可以让F#推断那里的大多数类型:

let test (left : _ Nullable) = if left.HasValue then left.Value else 0

Console.WriteLine(test (Nullable()))
Console.WriteLine(test (Nullable(100)))

let x = 100
Console.WriteLine(test (Nullable(x)))

您还可以使用active pattern在可空类型上应用模式匹配:

let (|Null|Value|) (x: _ Nullable) =
    if x.HasValue then Value x.Value else Null

let test = // this does exactly the same as the 'test' function above
    function
    | Value v -> v
    | _ -> 0

我前段时间写过关于nullable types in F# [/ shameless_plug]

的博客
相关问题