在 C# 中使用静态变量是否会妨碍安全编码实践

本文关键字:安全 编码 是否 变量 静态 | 更新日期: 2023-09-27 18:34:00

我是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# 中使用静态变量的线程,但我想知道,从安全角度来看,这是否是标准做法。我担心在整个程序执行过程中,变量驻留在内存中的同一位置。

通常有没有其他更好的方法来在各种函数之间共享变量。

在 C# 中使用静态变量是否会妨碍安全编码实践

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# 书籍,或在线搜索。