简体   繁体   中英

Is there only one instance of a static variable per process?

If I have the following class:

public class MyClass { public static int MyStaticInt = 0; }

If in the one solution I refer to MyNameSpace.MyClass.MyStaticInt in two different assemblies, am I referring to the same variable?

Static state is scoped per AppDomain by default and can be configured to be by thread if you use the ThreadStatic attribute.

This means that your assumption is valid if the assemblies are running in the same process and the process has only one application domain.

static can mean several things depending on context.

  • By default, you get one instance of the value per AppDomain .
  • If decorated with the ThreadStatic attribute, you get one instance of the value per thread.
  • If contained within a generic class, you get one instance of the value per concrete type.

For your example code, the first condition appears to be the case. In all cases, the specific assembly that the data is defined in does not make any difference.

Yes, there is only one instance per process per class.

A small caveat to this is when you have generic classes where you have one instance of the variable per instance of the generic class. Ie you would have one instance for MyGenericClass and one for MyGenericClass.

EDIT

In fact there is one instance per AppDomain, so you can create multiple copies by creating mulitple copies of the AppDomain yourself.

,MyClass.MystaticInt只是MyClass类的本地。

I've tested the static instance in a " custom " assembly, which is loaded from two locations: the main program (3rd party) and my " home-made " plugin that is loaded also by the main program. I've checked the AppDomain - it is exactly the same when the " custom " assembly is loaded from both places, alas the static instance of an object in a " custom " assembly is not the same. Therefore I have to conclude that static instance has the aforementioned single value per AppDomain per loaded assembly, if the assembly is loaded again, then it will not be the same.

class variable are static. there is only one occurance of a class variable per jvm per classloader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM