相关疑难解决方法(0)

为什么None表示为null?

CompilationRepresentationFlags.UseNullAsTrueValue 可以用来

允许使用null作为歧视联盟中的否定鉴别器的表示

Option.None 是这方面最突出的例子.

为什么这有用?如何检查空检查比检查联合情况(生成的Tag属性)的传统机制更好?

它可能导致意外的行为:

Some(1).ToString() //"Some(1)"
None.ToString()    //NullReferenceException
Run Code Online (Sandbox Code Playgroud)

编辑

我测试了Jack的断言,即与null相比,而不是静态只读字段更快.

[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
type T<'T> =
  | Z
  | X of 'T

let t = Z
Run Code Online (Sandbox Code Playgroud)

使用ILSpy,我可以看到t编译为null(如预期的那样):

public static Test.T<a> t<a>()
{
    return null;
}
Run Code Online (Sandbox Code Playgroud)

考试:

let mutable i = 0
for _ in 1 .. 10000000 do
  match t with
  | Z -> i <- i + 1
  | _ -> ()
Run Code Online (Sandbox Code Playgroud)

结果:

Real:00:00:00.036,CPU:00:00:00.046,GC gen0:0,gen1:0,gen2:0

如果CompilationRepresentation删除该属性,则t成为静态只读字段:

public static Test.T<a> t<a>() …
Run Code Online (Sandbox Code Playgroud)

f# discriminated-union

14
推荐指数
2
解决办法
1120
查看次数

标签 统计

discriminated-union ×1

f# ×1