小编典典

C#中静态变量的用途是什么?什么时候使用?为什么我不能在方法内部声明静态变量?

c#

我已经在C#中搜索了静态变量,但是我仍然不了解它的用途。另外,如果我尝试在方法内部声明变量,则不会授予我执行此操作的权限。为什么?

我看过一些有关静态变量的示例。我已经看到我们不需要创建类的实例来访问变量,但这不足以了解其用途以及何时使用它。

第二件事

class Book
{
    public static int myInt = 0;
}

public class Exercise
{
    static void Main()
    {
        Book book = new Book();

        Console.WriteLine(book.myInt); // Shows error. Why does it show me error?
                                       // Can't I access the static variable 
                                       // by making the instance of a class?

        Console.ReadKey();
    }
}

阅读 683

收藏
2020-05-19

共1个答案

小编典典

一个static变量,股吧之类的所有实例中的价值。

没有声明为静态的示例:

public class Variable
{
    public int i = 5;
    public void test()
    {
        i = i + 5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}

说明:如果您看上面的示例,我只声明int变量。当我运行此代码时,输​​出将为1010。这很简单。

现在让我们看一下这里的静态变量。我将变量声明为static

静态变量示例:

public class Variable
{
    public static int i = 5;
    public void test()
    {
        i = i + 5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}

现在,当我运行上述代码时,输​​出将为1015。因此,静态变量值在该类的所有实例之间共享。

2020-05-19