VB6中的私有静态在C#中?

ble*_*lez 5 .net c# java vb6

在VB6中,有一些本地静态变量在程序退出后保留它们的值.这就像使用公共变量但在本地块上.例如:

sub count()
static x as integer
x = x + 1
end sub
Run Code Online (Sandbox Code Playgroud)

在10次调用之后,x将是10.我试图在.NET中搜索相同的东西(甚至是Java),但没有.为什么?它是否以某种方式打破了OOP模型,并且有一种方法可以模拟它.

Mar*_*ell 6

你可以得到的最接近的是方法之外的静态字段:

private static int x;
public [static] void Foo() {
    x++;
}
Run Code Online (Sandbox Code Playgroud)

按要求关闭示例:

using System;
class Program {
    private static readonly Action incrementCount;
    private static readonly Func<int> getCount;
    static Program() {
        int x = 0;
        incrementCount = () => x++;
        getCount = () => x;
    }
    public void Foo() {
        incrementCount();
        incrementCount();
        Console.WriteLine(getCount());
    }
    static void Main() {
        // show it working from an instance
        new Program().Foo();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 使用静态构造函数初始化带有闭包的委托字段在访问变量方面可能稍微接近(与静态字段不同,它不会通过类上的反射或其他类方法可见)看到 (2认同)