c# 静态变量与非静态变量
Inside a function, you can initialize a static variable using the static
keyword.
在函数内部,可以使用static
关键字初始化静态变量 。
I said “inside a function”, because global variables are static by default, so there’s no need to add the keyword.
我说“在函数内部”是因为默认情况下全局变量是静态的,因此无需添加关键字。
What’s a static variable? A static variable is initialized to 0 if no initial value is specified, and it retains the value across function calls.
什么是静态变量? 如果未指定初始值,则静态变量将初始化为0,并在函数调用期间保留该值。
Consider this function:
考虑以下功能:
int incrementAge() {
int age = 0;
age++;
return age;
}
If we call incrementAge()
once, we’ll get 1
as the return value. If we call it more than once, we’ll always get 1 back, because age
is a local variable and it’s re-initialized to 0
on every single function call.
如果我们调用一次incrementAge()
,我们将获得1
作为返回值。 如果我们多次调用它,我们总是会得到1,因为age
是一个局部变量,并且在每次调用函数时都会将其重新初始化为0
。
If we change the function to:
如果将函数更改为:
int incrementAge() {
static int age = 0;
age++;
return age;
}
Now every time we call this function, we’ll get an incremented value:
现在,每次调用此函数时,我们将获得一个递增的值:
printf("%d\n", incrementAge());
printf("%d\n", incrementAge());
printf("%d\n", incrementAge());
will give us
会给我们
1
2
3
We can also omit initializing age
to 0 in static int age = 0;
, and just write static int age;
because static variables are automatically set to 0 when created.
我们也可以省略初始化age
在0 static int age = 0;
,并只写static int age;
因为静态变量在创建时会自动设置为0。
We can also have static arrays. In this case, each single item in the array is initialized to 0:
我们也可以有静态数组。 在这种情况下,数组中的每个项目都初始化为0:
int incrementAge() {
static int ages[3];
ages[0]++;
return ages[0];
}
c# 静态变量与非静态变量