C#中静态变量有什么用?什么时候使用?为什么我不能在方法中声明静态变量? [英] What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

查看:20
本文介绍了C#中静态变量有什么用?什么时候使用?为什么我不能在方法中声明静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have searched about static variables in C#, but I am still not getting what its use is. Also, if I try to declare the variable inside the method it will not give me the permission to do this. Why?

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

I have seen some examples about the static variables. I've seen that we don't need to create an instance of the class to access the variable, but that is not enough to understand what its use is and when to use it.

第二件事

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();
    }
}

推荐答案

static 变量在类的所有实例之间共享它的值.

A static variable shares the value of it among all instances of the class.

不将其声明为静态的示例:

Example without declaring it 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.很简单.

Explanation: If you look at the above example, I just declare the int variable. When I run this code the output will be 10 and 10. Its simple.

现在我们来看看这里的静态变量;我将变量声明为 static.

Now let's look at the static variable here; I am declaring the variable as a 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.所以静态变量值在该类的所有实例之间共享.

Now when I run above code, the output will be 10 and 15. So the static variable value is shared among all instances of that class.

这篇关于C#中静态变量有什么用?什么时候使用?为什么我不能在方法中声明静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆