F#:可为空的T支持 [英] F#: Nullable<T> Support

查看:89
本文介绍了F#:可为空的T支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)))

推荐答案

恐怕F#中没有可空类型的语法糖(与C#不同,在C#中您只需将?附加到类型中).是的,您在此处显示的代码看上去确实很冗长,但这是在F#中使用System.Nullable<T>类型的唯一方法.

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 the System.Nullable<T> type in F#.

但是,我怀疑您真正想要使用的是 选项类型 . MSDN页面上有一些不错的示例:

However, I suspect what you really want to be using are option types. There's a few decent examples on the MSDN page:

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#互操作).实现上的区别在于,选项类型由None区分联合形成,而Nullable<T>是BCL中的常规类,C#中有一些语法糖

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) and None, whereas Nullable<T> is a normal class in the BCL, with a bit of syntactical sugar in C#.

这篇关于F#:可为空的T支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆