gpt4 book ai didi

F# 选项...它们真的能防止空引用异常吗

转载 作者:行者123 更新时间:2023-12-03 10:07:11 28 4
gpt4 key购买 nike

我在看《Professional F# 2.0》一书作者展示如下代码

let a string : option = None
if a.IsNone then
System.Console.WriteLine("a is none")
else
System.Console.WriteLine("a is some");;

然后说

“这使得 Option 的使用大大优于 null 的使用,并且在消除运行时抛出的异常的重要来源方面大有帮助”

好的。所以我写
System.Console.WriteLine(a.GetType());;

我得到

System.NullReferenceException:未将对象引用设置为对象的实例。
在 System.Object.GetType()
在 .$FSI_0008.main@()
由于错误而停止

而我就像'un!!!”

如何真正做一个
if a.isSome then
do bla bla

any different from

if a != null then
do bla bla

所以我不明白程序员是如何从 NullPointers 中保存下来的

PS:NullPointerException 过去让我很伤心。

最佳答案

F# 编译器不会阻止您 NullReferenceException完全地。当您使用 .NET 中定义的类型时,您仍然可以获得 null值,因为 F# 无法阻止这种情况。

但是,当您使用在 F# 中声明的类型时,编译器不允许创建 null该类型的值,因此它避免了 NullReferenceException在这种情况下。例如,以下代码无法编译:

type Person(name:string) = 
member x.Name = name

// 'Person' is a type declared in F#, so the argument cannot be 'null' in safe code
let printName (person:Person) =
printfn "%s" person.Name

// Compiler error here - 'null' is not a valid value of 'Pereson' type
printName null

当您使用 option<Person>作为参数,那么您必须明确检查 NoneSome案件。最好使用 match 来完成。 ,它检查您没有遗漏任何情况。例如:
let printName (person:option<Person>) = 
match person with
// You get a warning here, saying that you're not handling the 'None' case!
| Some person -> printfn "%s" person.Name

警告告诉您应该添加案例处理 None .你仍然可以编译代码,但你不会得到 NullReferenceException使用 F# 类型时,如果您不忽略警告。

另见 this great, related StackOverflow post .

关于F# 选项...它们真的能防止空引用异常吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11330186/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com