有关非静态类和垃圾回收中的静态成员的问题 [英] A question about static members inside non-static classes and garbage collection

查看:124
本文介绍了有关非静态类和垃圾回收中的静态成员的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个同事声称,在C#中具有非静态类中的静态成员的C#可以防止垃圾回收这些类的实例,并且这是C#内存泄漏的常见原因.结果,他总是将静态成员包装在静态类中,并通过该静态类上的静态属性或方法从那里访问它们.我一直以为静态变量在堆栈上,而不是堆上,因此与垃圾回收没有任何关系.在我看来,这不合适.

这是什么事实?

解决方案

他不知道自己在说什么.非静态类中的静态成员不会阻止垃圾回收该类的实例.

也就是说,静态变量可以位于堆栈或堆中.垃圾回收无关紧要.重要的是类型的静态部分不会与该类型的实例一起存储.

A collegue of mine claims that in C# having static members in non-static classes prevents instances of those classes from ever being garbage collected and that this is a common source of C# memory leaks. As a result he always wraps static members in a static class and gains access to them from there via a static property or method(s) on that static class. I always thought that statics were on the stack, not the heap and so did not have anything to do with the garbage collection. It does not seem right to me.

What is the truth about this?

解决方案

He doesn't know what he's talking about. Static members inside a non-static class do not prevent instances of the class from being garbage collected.

That said, statics can be on the stack or heap. It doesn't matter for garbage collection. What does matter is that the static parts of a type are not stored with instances of the type.

这篇关于有关非静态类和垃圾回收中的静态成员的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆