Home Backend Development C#.Net Tutorial C# Learning Diary 20----static static variables and constants

C# Learning Diary 20----static static variables and constants

Jan 21, 2017 pm 03:13 PM

In the previous article "Delegate (Delegate) Type", I used the static keyword when defining the public method, which resulted in the inability to access this method through the form of object.method name. In this article, we will learn more about static static variables. .

Variables:

Before learning static static variables, we still need to understand the meaning of variables. Programs need to perform operations such as reading, writing, and computing data. When a specific value or result needs to be saved, variables need to be used. From the user's perspective, a variable is the name used to describe a piece of information. Each variable can be stored in a variable. Various types of information, such as: a person's name, the price of a ticket, etc.; from the computer's perspective, the variable represents the storage address, what type the variable is, and what type of value is stored in the variable. An important principle when using variables is that variables must be defined first and then used.

The definition and usage rules of variables in C# are similar to those in C/C++, so I won’t go into details here (so it is quite important to learn C well^_^)

static static variable:

Variables declared with the static modifier are called static variables. Once the class to which the static variable belongs is loaded, it will exist until the end of the program containing the class. There are two main properties of static:

1. Hidden:

Static methods or static variables defined in a class belong to the class itself, not to an object of that class. To call a method defined as static, it must be preceded by the name of the class. (Even public access modification will not work, which is why at the end of the previous article) Instance methods must be used through instances of the class. Instance methods can use non-static members of the class as well as static members of the class.

Access rules:

Static methods can only access static members of the class and cannot access non-static members of the class;
Non-static methods can access static members of the class and can also access the class Non-static members;
Static methods cannot be called using instances, but can only be called using class names.

For example, the following example:

class person  
    {  
       public static int i;   //定义一个静态变量i 默认值是0  
       public int k=0;         //定义一个非静态变量 k;  
       public static int sbu()   // 定义一个静态方法   
       {  
           i = 9;  //成功对静态变量赋值  
           k = 5;  //出错了,无法访问非静态变量  
           return k;  
           //综上静态方法只能访问静态变量  
       }  
        public int Add()  //定义一个实例方法  
        {  
            i = 9;    //对静态变量赋值没有问题  
            k = 5;    //对非静态变量赋值也没问题  
            return i;  
            //综上实例方法能够访问所有类型变量  
        }  
  
    }
Copy after login

We instantiate a person and an object to access the method:

static void Main(string[] args)  
        {  
            person per = new person();   //实例化一个对象per  
           int i = per.i;   //出错了,per访问不了类里的静态变量  
            int k = per.k; //没有问题  
            per.sbu(); //出错了,per访问不了静态方法  
            person.sbu();  //成功调用  
            per.Add();   //成功调用  
            person.Add();  //出错了,person访问不了实例方法  
              
        }
Copy after login

2. Keep the variable content persistent:

The variables stored in the static data area will be initialized when the program starts, and it is also the only initialization. There are two types of variables stored in the static storage area: global variables and static variables. However, compared with global variables, static can control the visible range of variables. After all, static is used to hide.

Just write an example and you will know (this time I wrote it in C++) C# does not allow the use of static in methods:

#include<iostream>  
  
using namespace std;  
  
int main()  
{  
   for (int i=0;i<4;i++)  
   {  
      static int k =0;   //定义一个静态变量并赋值为0   
      k++;  
      cout<<k<<endl;  //输出  
   }  
    
   return 0;  
  
}
Copy after login

Result:

C# Learning Diary 20----static static variables and constants

If we remove static in the above code, then k=0; becomes a non-static variable, and the result will only be a number 1;

Constant:

A constant is a quantity whose quality is fixed. From the perspective of data type, the type of a constant can be any value type or reference type. The declaration of a constant is to declare the constant name and its value to be used in the program. (Usage is also similar to C) But in C#, once a constant is defined, its value cannot be changed

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace demo  
{  
    class Program  
    {  
        const int S = 9;  // 定义一个常量S并赋值  
        static void Main(string[] args)  
        {  
            S += 4;  //出错了,常量一旦定义就不能改变常量的值  
           Console.WriteLine(S);  
        }  
    }  
}
Copy after login

The above is the content of C# Learning Diary 20----static static variables and constants, more related content Please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the static variable mechanism of PHP functions? What is the static variable mechanism of PHP functions? Apr 10, 2024 pm 09:09 PM

The static variable mechanism of PHP functions allows variables to retain their values ​​between function calls, thus achieving the following functionality: Preserving state between function calls. Avoid creating duplicate variables. Simplify the code.

What is the function and usage of static in C language What is the function and usage of static in C language Jan 31, 2024 pm 01:59 PM

The role and usage of static in C language: 1. Variable scope; 2. Life cycle; 3. Internal function; 4. Modify global variables; 5. Modify function; 6. Other uses; Detailed introduction: 1. Variable scope, when If there is the static keyword before a variable, then the scope of the variable is limited to the file in which it is declared. In other words, the variable is a "file-level scope", which is very useful for preventing the "duplicate definition" problem of variables; 2. Life cycle, static variables are initialized once when the program starts executing, and destroyed when the program ends, etc.

How to use static, this, super, and final in Java How to use static, this, super, and final in Java Apr 18, 2023 pm 03:40 PM

1. static Please look at the following program first: publicclassHello{publicstaticvoidmain(String[]args){//(1)System.out.println("Hello, world!");//(2)}} Have seen this Segment programs are familiar to most people who have studied Java. Even if you have not learned Java but have learned other high-level languages, such as C, you should be able to understand the meaning of this code. It simply outputs "Hello, world" and has no other use. However, it shows the main purpose of the static keyword.

Practical application scenarios and usage skills of the static keyword in C language Practical application scenarios and usage skills of the static keyword in C language Feb 21, 2024 pm 07:21 PM

Practical application scenarios and usage skills of the static keyword in C language 1. Overview static is a keyword in C language, used to modify variables and functions. Its function is to change its life cycle and visibility during program running, making variables and functions static. This article will introduce the actual application scenarios and usage techniques of the static keyword, and illustrate it through specific code examples. 2. Static variables extend the life cycle of variables. Using the static keyword to modify local variables can extend their life cycle.

How to use Java modifiers abstract, static and final How to use Java modifiers abstract, static and final Apr 26, 2023 am 09:46 AM

Modifier abstract (abstract) 1. Abstract can modify a class (1) The class modified by abstract is called an abstract class (2) Syntax: abstractclass class name {} (3) Features: Abstract classes cannot create objects separately, but they can be declared Reference the abstract class name reference name; (4) Abstract classes can define member variables and member methods (5) Abstract classes have constructors. When used to create subclass objects, jvm creates a parent class object by default; abstract constructor methods apply Applied when jvm creates parent class object. 2. Abstract can modify methods (1) The method modified by asbtract is called an abstract method (2) Syntax: access modifier abstract return value

The role of static The role of static Jan 24, 2024 pm 04:08 PM

The functions of static: 1. Variables; 2. Methods; 3. Classes; 4. Other uses; 5. Multi-threaded environment; 6. Performance optimization; 7. Singleton mode; 8. Constants; 9. Local variables; 10. Memory Layout optimization; 11. Avoid repeated initialization; 12. Use in functions. Detailed introduction: 1. Variables, static variables. When a variable is declared as static, it belongs to the class level, not the instance level, which means that no matter how many objects are created, only one static variable exists, and all objects share this Static variables and so on.

How Springboot reads custom pro files and injects static variables How Springboot reads custom pro files and injects static variables May 30, 2023 am 09:07 AM

Springboot reads the pro file and injects static static variables mailConfig.properties#Server mail.host=smtp.qq.com#Port number mail.port=587#Email account mail.userName=hzy_daybreak_lc@foxmail.com#Email authorization code mail.passWord =vxbkycyjkceocbdc#Time delay mail.timeout=25000#Sender mail.emailForm=hzy_daybreak_lc@foxmail.com#Sender mai

What is the static method of php What is the static method of php Oct 31, 2022 am 09:40 AM

The "static" in php static static methods means that these properties and methods can be called directly without instantiating the class; static is a keyword used to modify the properties and methods of the class, and its usage syntax is such as "class Foo {public static $my_static = 'hello';}".

See all articles