我正在阅读“专业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");;然后说
“这使得选项的使用大大优于null的使用,并大大有助于消除运行时抛出的异常的重要来源”
好的。所以我写
System.Console.WriteLine(a.GetType());;我得到了
System.NullReferenceException:对象引用没有设置为对象的实例。在System.Object.GetType() at .$FSI_0008.main@()时,由于错误而停止
我就像‘不!!’“
到底是怎么做的
if a.isSome then
do bla bla
any different from
if a != null then
do bla bla所以我看不出程序员是如何从NullPointers中被拯救出来的
PS: NullPointerException在过去给我带来了很多悲伤。
发布于 2012-07-04 19:09:35
为了补充Tomas的答案,Option类型的一个主要好处在于它支持的高阶函数,这些函数给您提供了更简洁和更安全的功能。您可能会发现关于这个主题的我的博客文章很有用。
发布于 2012-07-04 13:58:07
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>作为参数时,必须显式检查None和Some情况。最好使用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#。
https://stackoverflow.com/questions/11330186
复制相似问题