在VB6中,有一些本地静态变量在程序退出后保留它们的值.这就像使用公共变量但在本地块上.例如:
sub count()
static x as integer
x = x + 1
end sub
Run Code Online (Sandbox Code Playgroud)
在10次调用之后,x将是10.我试图在.NET中搜索相同的东西(甚至是Java),但没有.为什么?它是否以某种方式打破了OOP模型,并且有一种方法可以模拟它.
你可以得到的最接近的是方法之外的静态字段:
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)
| 归档时间: |
|
| 查看次数: |
538 次 |
| 最近记录: |