基类中的静态成员是否在其派生类之间共享
这个问题专门针对.Net。
假设基类 A 有 2 个派生类 B 和 C。此外,假设基类 A 有一个名为 's' 的静态变量。该静态变量值是否在“B”和“C”之间共享,或者每个都获得自己的静态变量副本。
我目前的知识表明,通常静态变量在派生类之间共享,除非基类是通用的。如果基类是泛型,则为其类型参数的每个唯一组合创建该类的唯一副本,并且该类的每个此类副本与该特定副本的派生类一起共享来自基类的相同静态变量。
我实际上面临着一个非常独特的情况。就我而言,A、B 和 C 都是非泛型的。 A 有一个静态成员。但是这个成员的值对于 B 和 C 来说是不同的,根据我的理解,情况不应该是这样的(除非我上面对静态变量的声明是不正确的)。
编辑:
我的应用程序是一个 ASP.NET 应用程序。我正在继续调试它,但根据我当前的评估,它是这样发生的:
- 我在变量发生更改的地方放置了一个断点,并且在第一次命中断点时其值得到更新。
- 下次命中断点时,该变量将恢复到其旧值并再次初始化。它是一个私有变量,仅在一个地方发生变化。
我的猜测是应用程序应用程序域可能已回收,或者以某种方式从内存中卸载了该类。我还在调查这个问题,但谢谢大家的回复。
The question regards .Net specifically.
Suppose a base class A has 2 derived classes B and C. Further, suppose base class A has a static variable called 's'. Is this static variable values shared between 'B' and 'C', or does each get its own copy of the static variable.
My current knowledge says that normally the static variable is shared between derived classes, unless the base class is Generic. If the base class is generic, then a unique copy of the class is created for each unique combination of its type parameters, and each such copy of the class together with that particular copy's derived classes share the same satatic variable from the base class.
I am actually facing a very unique situation. In my case, all of A, B and C are non-generic. And A has a static member. But the value for this member is different for B and C, which in my understanding should not have been the case (unless my above statement for static variables is incorrect).
EDIT:
Well my application is an ASP.NET app. I am continuing to debug this, but as per my current assessment, its happening like this:
- I put a breakpoint where the variable is changed and its value gets updated the first time the breakpoint is hit.
- The next time the breakpoint is hit, the variable has reverted back to its old value and is initialized again. It's a private variable and only changed in a single place.
My guess is maybe either the application app domain has recycled or somehow otherwise the class was unloaded from memory. I am investigation this still, but thanks everyone for the replies.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你能展示一些代码吗?
测试控制台代码
测试控制台结果
Could you show some code?
Test console code
Test console result
基类中的静态成员在派生类之间共享。您看到的变量值应该在用于访问它的不同派生类中保持一致。
the static member in base class is shared between the derived classes. The value you would see for the variable should be consistent across different derived classes you use to access it.