1

我是 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)   

    }

}
  1. 静态变量i可用于该类中的所有函数。
  2. 然后是I ,它与代码中的每个函数共享i ,因为它是公开的。- 不知道我是否应该这样做。

我确实找到了关于在 C# 中使用静态变量的线程,但我想知道,从安全角度来看,这是否是一种标准做法。我担心变量在整个程序执行过程中驻留在内存中的同一位置。

一般来说,有没有其他更好的方法可以在各种函数之间共享一个变量。

4

1 回答 1

2
static int i = 0; // A private static integer

在这里,您声明了一个静态成员。到目前为止,一切都很好。

static void Main(string[] args)
{
    int i = 1;// The main function is changing this integer
}

不,它没有。int i意味着您声明了一个名为i.

void reset() { 
    int i = 0;// another function is changing the value of integer i
}

不,它没有。int i意味着您声明了一个名为i.

我想知道从安全角度来看这是否是一种标准做法。

不,它不是,不,它与安全性无关。您应该尽可能避免使用静态成员。我认为目前的实际原因您当前的知识和理解水平相去甚远。只需将其作为最佳实践即可。

我担心变量在整个程序执行过程中驻留在内存中的同一位置。

好吧,在内存位置之间“移动”的变量不是一个好主意:-) 变量很简单地说就是内存中的命名位置。

一般来说,有没有其他更好的方法可以在各种函数之间共享一个变量。

是的,首先要了解函数参数、成员字段和属性。使用任何可用的初学者 C# 书籍,或在线搜索。

于 2016-02-10T16:51:18.470 回答