gpt4 book ai didi

f# - 为什么这里的盒子?

转载 作者:行者123 更新时间:2023-12-01 11:26:59 24 4
gpt4 key购买 nike

在浏览 StackOverflow 时,我偶然发现了以下答案:

https://stackoverflow.com/a/3817367/162694

// ... removed unneeded code
/// This type is intended for private use within Singleton only.
type private SyncRoot = class end

type Singleton =
[<DefaultValue>]
static val mutable private instance: Singleton

private new() = { }

static member Instance =
lock typeof<SyncRoot> (fun() ->
// vvv
if box Singleton.instance = null then
// ^^^
Singleton.instance <- Singleton())
Singleton.instance

有人可以详细说明为什么需要此处的 box 吗?

最佳答案

给定Singleton类型没有 null作为一个适当的值。换句话说,它不可为 null,通常不应具有值 null。 .因此,比较 Singleton 类型的值是不明智的。与 null , 即使通过 [<DefaultValue>] 使用未初始化的变量可以创建此类型的空值变量。拳击将任何东西变成 obj ,它可以为 null,因此在此上下文中有效。

使用 Unchecked.defaultof<Singleton>而不是 null将使装箱变得不必要并编译。 (还有 [<AllowNullLiteral>] 属性,可以将其添加到 Singleton 类型以指定此类型的实例可以是 null 。)

关于f# - 为什么这里的盒子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36533179/

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