简体   繁体   English

非静态类中私有静态变量的范围

[英]Scope of private static variable in non static class

I know that, a static property can persist its value as long as the application remains running. 我知道,只要应用程序保持运行状态,静态属性就可以保留其值。 Will it be same for a private static field inside non static class 非静态类中的私有静态字段是否相同

public class A
{
   private static int B;

   public int GetSession()
   {
     return B++;
   }
}

In above class i have a private static field. 在上述类中,我有一个私有静态字段。 Will calling GetSession() method will provide number of times the GetSession() accessed? 调用GetSession()方法将提供访问GetSession()的次数吗?

Since B is static it'll be shared between all sessions; 由于Bstatic它将在所有会话之间共享 the thread-safe (what if two sessions are trying to access / increment it simultaneously ?) implementation is 线程安全的(如果两个会话试图访问/ 同步增加吗?)实施

   public int GetSession()
   {
       return Interlocked.Increment(ref B);
   }

Edit: If we want to emulate B++ , not ++B (and return B before incrementing - see Jeppe Stig Nielsen's comment) we can just subract 1 : 编辑:如果我们要模拟B++ ,而不是++B (并递增之前返回B请参见Jeppe Stig Nielsen的评论),我们可以简单地算出1

   public int GetSession()
   {
       // - 1 Since we want to emulate B++ (value before incrementing), not ++B
       return Interlocked.Increment(ref B) - 1;
   }

Yes, it will provide the number of times the GetSession() method was called. 是的,它将提供调用GetSession()方法的次数。

It will be the total over all instances of A . 这将是A 所有实例的总数。

Note that it is not thread safe, so if your application has multiple threads potentially calling GetSession() concurrently, the count may be wrong. 请注意,它不是线程安全的,因此,如果您的应用程序有多个线程可能同时调用GetSession() ,则计数可能是错误的。 See Dmitry Bychenko's answer. 参见德米特里·拜琴科的答案。 This is no problem if all your instances of A are being called from the same thread. 如果您的A所有实例都在同一线程中调用,这没有问题。

Also note, that if your application has several AppDomains, each AppDomain will have a separate static field. 还要注意,如果您的应用程序具有多个AppDomain,则每个AppDomain将具有一个单独的静态字段。 So then it counts only invocations from within the same AppDomain, regardless of which instance the calls went through. 因此,无论调用经过哪个实例,它仅计入同一AppDomain中的调用。

Yes it will still return the number of times B was accessed. 是的,它仍将返回访问B的次数。 It's still static . 它仍然是static Adding private does not change this. 添加私有不会更改此设置。 And making the class static means that an object cannot be instantiated for that class, therefore, everything in the class would need to be static . 将类设为static意味着无法为该类实例化对象,因此,该类中的所有内容都必须为static But the variable will still behave the same. 但是该变量的行为仍然相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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