我是 C# 编程的新手,我目前在我的代码中使用了许多静态变量。下面是一个例子:
class Program
{
public int I//Can be used to access the variable i anywhere from the code as it is public
{
get { return i; }
set { i = value; }
}
static int i = 0; // A private static integer
static void Main(string[] args)
{
i = 1;// The main function is changing this integer
}
void reset() {
i = 0;// another function is changing the value of integer i
}
}
class otherclass
{
void otherreset()
{
Program program = new Program();
program.I = 1;// another function in another class is changing the value of integer i(indirectly)
}
}
- 静态变量i可用于该类中的所有函数。
- 然后是I ,它与代码中的每个函数共享i ,因为它是公开的。- 不知道我是否应该这样做。
我确实找到了关于在 C# 中使用静态变量的线程,但我想知道,从安全角度来看,这是否是一种标准做法。我担心变量在整个程序执行过程中驻留在内存中的同一位置。
一般来说,有没有其他更好的方法可以在各种函数之间共享一个变量。