gpt4 book ai didi

c# - 如果结构可以实现 IDisposable,为什么它们不能有析构函数?

转载 作者:太空狗 更新时间:2023-10-30 01:13:30 25 4
gpt4 key购买 nike

我阅读了类似 question 的已接受答案,部分答案是:

when structs are passed as parameters, they get passed by value: they are copied. Now you've got two structs with the same internal fields, and they're both going to attempt to clean up the same object. One will happen first, and so code that is using the other one afterwards will start to fail mysteriously... and then its own cleanup will fail

Dispose() 不是同样的问题吗?如果结构可以实现 IDisposable,那么不允许它们具有终结器的原因是什么?

如果终结器的全部意义在于调用 Dispose(false) 以防程序员忘记调用 Dispose(),并且结构可以具有 IDisposable .Dispose(),那么为什么不允许结构的终结器但允许它们用于引用类型?

最佳答案

Doesn't this same problem apply to Dispose()?

有点,但不完全是。具体来说,“然后它自己的清理将失败”是可能的,但不太可能,因为 Dispose()在同一对象上多次调用必须是安全的,并且在同一对象的不同副本上多次调用它通常不会有问题。

If structs can't have finalizers, why are they allowed to implement IDisposable?

允许它是自然行为;它为语言提供了更简单的规则。由于这不是程序员可能偶然出错的事情,因此在编译器中编写额外代码来拒绝这种情况的好处很小。


Jeroen Mostert 补充说,它甚至可以使结构实现很有意义 IDisposable :

IDisposable可能只是因为它是一些其他代码的要求而被实现,即使 Dispose()在此特定类型上的实现绝对不会做任何事情。在这种情况下,不存在在不同副本上意外调用它的风险。这方面的一个例子是当结构实现 IEnumerator<T> 时, 其中IEnumerator<T>反过来实现IDisposable .

关于c# - 如果结构可以实现 IDisposable,为什么它们不能有析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50132441/

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