为什么 LazyInit是这样的? 仅限于引用类型

发布于 2024-07-08 17:41:31 字数 176 浏览 13 评论 0原文

我有一个伪实时数据处理应用程序,我想在其中使用 LazyInit,这样我就不会进行不需要的计算,但是 LazyInit > 将 T 限制为类。 我可以解决这个问题,但我显然不想这样做。

有人知道这是为什么吗?

I have a pseudo-realtime data processing application where I would like to use LazyInit<double> so I don't do calculations I don't need, but LazyInit<T> restricts T to classes. I can work around it, but I'd obviously prefer not to.

Does anybody know why this is?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

国粹 2024-07-15 17:41:31

我们当前(预览)位仅提供 LazyInit 类型,正如您所观察到的(JaredPar 正确诊断),我们将 T 限制为引用类型,以便我们可以:(i)使 LazyInit 成为结构体,以及(ii)通过提供合理的默认行为CMPXCHG(即,我们可以检查“null”以表示不存在值)。 我们本来可以使 T 不受限制,但决定针对常见情况进行优化——否则就意味着一些额外的字节; 不管你相信与否,这可能会让这种类型对某些人来说变得昂贵得令人望而却步。

我们最近稍微改变了路线。 目前,我们计划除了 T 仅限于引用类型的 LazyInitField 类型之外,还提供 T 不受限制的 LazyInit 类型。 前者是大多数人会使用的,但后者可以用于那些有完美意识并且可以忍受 T 限制的人。

希望这能解决问题。 干杯,

--joe duffy,pfx 开发负责人

Our current (preview) bits only provide a LazyInit type, and as you observed (and JaredPar correctly diagnosed) we restrict T to reference types so that we can: (i) make LazyInit a struct, and (ii) provide reasonable default behavior via CMPXCHG (i.e., we can check for 'null' to mean the absence of a value). We could have made T unrestricted, but decided to optimize for the common case -- doing otherwise would have meant a few extra bytes; believe it or not, this might've made the type prohibitively expensive for some folks.

We've recently changed course slightly. We currently plan to offer a LazyInit type where T is unrestricted in addition to a LazyInitField type where T is restricted to reference types. The former is what most people will use, but the latter can be used for those who are perf-conscious and can live with the restriction on T.

Hope this clears things up. Cheers,

---joe duffy, pfx dev lead

始终不够 2024-07-15 17:41:31

原因是 LazyInit 中的底层 API 选择。 它使用 Interlocked.CompareExchange 来进行线程安全值设置。 CompareExchange 而泛型则仅限于使用类类型。 因此 LazyInit 的 T 值也必须是一个类。

您可以在此处查看实现: LazyInit

The reason why is an underyling API choice in the LazyInit. It uses Interlocked.CompareExchange in order to do a thread safe value set. CompareExchange while generic is constrained to only use class types. Therefore the T value of LazyInit must also be a class.

You can view the implementation here: LazyInit

不醒的梦 2024-07-15 17:41:31

我相信这是因为值类型是自动初始化的,LazyInit 根据它是否为 null 来确定是否需要初始化。 您可以通过使用可空类型来解决这个问题。

LazyInit<double?>

I believe it is because value types are automatically initialized and LazyInit determines if something needs initializing based on if it is null or not. You can get around it by using nullable types.

LazyInit<double?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文