c# - 为什么 WeakReference 不是结构体?

标签 c# .net memory-management garbage-collection

正如这篇文章所说:http://www.philosophicalgeek.com/2014/08/14/prefer-weakreferencet-to-weakreference/

If you are using WeakReference at all, it likely means you are somewhat memory conscious . In this case, allocating new WeakReference objects will contribute extra, unnecessary memory pressure.

所以在这种情况下,将它变成一个结构不是更有意义吗?并且在我们使用它时是不可变的,并摆脱 SetTarget()。

最佳答案

WeakReference WeakReference<T> 类都有终结器,wouldn't be possible if they were structs .

如果确实有必要,您可以使用 weak 创建自己的自定义弱引用结构。品种 GCHandle . (我相信,虽然我不确定,WeakReferenceWeakReference<T> 在内部使用 GCHandle,尽管它们的终结器确保一切都被正确清理。您的自定义结构需要处理它自己的清理-不求助于终结器。)

关于c# - 为什么 WeakReference 不是结构体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31320061/

相关文章:

c - 释放 C 中的 2D 数组。 "double free or corruption"和 "invalid next size"

c# - 以编程方式检查 Windows 服务是否正在运行 C#

c# - 录音机 c# UWP

.net - Fluent Interfaces - 正在创建的对象的数量

c# - 这是 LINQ 查询 "correct"吗?

android - 在组件和应用程序之间传递数据

c - 记录内存分配错误

javascript - 将对象数组从 JavaScript 发送到 C# Controller

c# - 使用 C# 将 JSON 字符串从 Camel 大小写转换为 Pascal 大小写

c# - Windows 8 上的 Matlab 生成器 NE/MCR