在 F# 中处理空值 [英] Handling Null Values in F#

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

问题描述

我需要使用 F# 与一些 C# 代码互操作.Null 是一个可能的值,因此我需要检查该值是否为空.文档建议使用模式匹配:

I need to interop with some C# code with F#. Null is a possible value that it is given so I need to check if the value was null. The docs suggest using pattern matching as such:

match value with
| null -> ...
| _ -> ...

我遇到的问题是原始代码在 C# 中的结构如下:

The problem I'm having is the original code is structured in C# as:

if ( value != null ) {
    ...
}

如何在 F# 中执行等效操作?模式匹配是否有空操作?有没有办法用 if 语句检查 null?

How do I do the equivalent in F#? Is there a no-op for pattern matching? Is there a way to check for null with an if statement?

推荐答案

如果你不想在null情况下做任何事情,那么你可以使用单位值():>

If you don't want to do anything in the null case, then you can use the unit value ():

match value with
| null -> ()
| _ -> // your code here

当然,您也可以像在 C# 中一样进行空检查,在这种情况下可能更清楚:

Of course, you could also do the null check just like in C#, which is probably clearer in this case:

if value <> null then
    // your code here

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

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