F# method returns null instead of Option

北慕城南 提交于 2019-12-04 07:42:15

In F# it is possible to represent one data-less value of a DU with the null constant at runtime. You can instruct the compiler to do so with CompilationRepresentationFlags.UseNullAsTrueValue:

[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
type A = B | C of int

printfn "%A" (obj.ReferenceEquals( B, null ))  // will print "true"

In the above code, the DU value B gets compiled to null. This is sometimes nice for optimization purposes: instead of allocating an instance every time, I use a constant. Helps if the value is used a lot.

So the Option type uses this same technique for the None case, and that's why None shows up as null in the debugger.

One day, the debugger will have appropriate extension points to implement this and other F# features. Until then, the debugger speaks C#, and you get to do the translation.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!