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

Akb*_*sha 5 c# asp.net static

我知道,只要应用程序保持运行,静态属性就可以保留其值。非静态类中的私有静态字段是否相同

public class A
{
   private static int B;

   public int GetSession()
   {
     return B++;
   }
}
Run Code Online (Sandbox Code Playgroud)

在上面的类中,我有一个私有静态字段。调用GetSession()方法会提供访问次数GetSession()吗?

Dmi*_*nko 2

因为B它将在所有会话之间static共享线程安全(如果两个会话试图同时访问/递增它怎么办?)实现是

   public int GetSession()
   {
       return Interlocked.Increment(ref B);
   }
Run Code Online (Sandbox Code Playgroud)

编辑:如果我们想模拟B++,而不是(并在递增之前++B返回- 请参阅 Jeppe Stig Nielsen 的评论),我们可以减去:B 1

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