F#:可空支持
在 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)))
What is the right way to use Nullable in F#?
Currently I'm using this, but it seems awefully messy.
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)))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
恐怕 F# 中没有可空类型的语法糖(与 C# 不同,在 C# 中您只需将
?
附加到类型)。 是的,您在那里显示的代码确实看起来非常冗长,但这是在 F# 中使用System.Nullable
类型的唯一方法。但是,我怀疑您真正想要使用的是 选项类型。 MSDN 页面上有一些不错的示例:
并且
显然使用起来要好得多!
选项本质上履行了 F# 中可空类型的作用,我认为您确实希望使用它们而不是可空类型(除非您正在与 C# 进行互操作)。 实现上的差异在于,选项类型由
Some(x)
和None
的可区分联合构成,而Nullable;
是 BCL 中的一个普通类,在 C# 中带有一些语法糖。I'm afraid there's no syntactical sugar for nullable types in F# (unlike in C# where you simply append a
?
to the type). So yeah, the code you show there does look terribly verbose, but it's the only way to use theSystem.Nullable<T>
type in F#.However, I suspect what you really want to be using are option types. There's a few decent examples on the MSDN page:
and
Clearly a lot nicer to use!
Options essentially fulfill the role of nullable types in F#, and I should think you really want to be using them rather than nullable types (unless you're doing interop with C#). The difference in implementation is that option types are formed by a discriminated union of
Some(x)
andNone
, whereasNullable<T>
is a normal class in the BCL, with a bit of syntactical sugar in C#.您可以让 F# 推断其中的大多数类型:
您还可以使用活动模式来应用可空类型的模式匹配:
我不久前在博客中介绍了 F# 中的可空类型 [/无耻_插件]
You can let F# infer most of the types there:
You can also use an active pattern to apply pattern matching on nullable types:
I blogged some time ago about nullable types in F# [/shameless_plug]