static 函数的理解及基安全性

    技术2022-05-11  6

    在web中你创建static 函数,要注意几个问题:

    1.因为在   public static是全局share的,假如你的static 函数含有static 变量的话,如下代码:

    private static string testa = "candue";        //static 变量    public static string Getstr1()    {        if (testa != "echo")        {            testa = "echo";        }        return testa;    }    public static string Getstr2()    {        return testa;    } 

    只要你调用Getstr1(),static string testa 以就会变成echo,其实人调用Getstr2()就变成echo,

    如果人家想取“candue”,这样就出问题了。static 是储存在内存中的,每个人都是问相同的内存地址取数。如果有任何一个人修改了这个内存地址的数据值时,所有人的取的数据都变了。所以这种写法不好。

    而且在线程安全性方面也不好。如果这个解决线程安全性的话。就要用单件模式。

    2.应该这样写法好:

    static 函数中不调用static 变量,这样每次取值时都会重新取值:如下代码:

     public static string Getstr3()    {        string aa = "candue";        return aa;    }

    不需要考虑纯程安全性问题。但要性能问题。


    最新回复(0)