在C语言中,我可以做到:
void foo() {
static int c = 0;
printf("%d,", c);
c ++;
}
foo();
foo();
foo();
foo();
它应该打印出 0,1,2,3
C# 中有类似的功能吗?
虽然有人建议使用静态
成员变量,但由于可见性不同,这并不相同。作为 aquinas 回答的替代方案,如果接受闭包,则可以这样做:
(请注意,Foo
是一个属性而不是方法,c
是“每个实例”的。)
class F {
public readonly Action Foo;
public F () {
int c = 0; // closured
Foo = () => {
Console.WriteLine(c);
c++;
};
}
}
var f = new F();
f.Foo(); // 0
f.Foo(); // 1
static
变量等同物。不,没有办法实现与静态C函数变量相同的行为...
类似如下:
class C
{
private static int c = 0;
public void foo()
{
Console.WriteLine(c);
c++;
}
}
c
对所有方法都是可见的。 - user166390C#中没有全局变量,但是你可以在类中创建静态字段。
public class Foo{
private static int c = 0;
void Bar(){
Console.WriteLine(c++);
}
}
WriteLine()
接受 object
数据类型。您不需要将其转换为字符串。只需执行:Console.WriteLine(c++);
- The Maskconst
而不是static
声明的,例如private static const int Zero = 0
。 - Rubenc
只能在它声明的作用域内可见。 - Jack你无法在方法级别上完成此操作。你可以在方法级别上实现最接近的方式是像这样做,但这并不是非常接近。特别地,它只在你拥有枚举器引用时才有效。如果其他人调用此方法,他们将看不到你的更改。
class Program {
static IEnumerable<int> Foo() {
int c = 0;
while (true) {
c++;
yield return c;
}
}
static void Main(string[] args) {
var x = Foo().GetEnumerator();
Console.WriteLine(x.Current); //0
x.MoveNext();
Console.WriteLine(x.Current); //1
x.MoveNext();
Console.WriteLine(x.Current); //2
Console.ReadLine();
}
}