C#面向对象基础(四) 静态成员与实例成员

类里的成员有两种归属划分静态的与实例的

静态成员 -> static声明

静态的成员,是属于"类"的

实例的成员,属于"类的实例"的

 1     class Program
 2     {
 3         static int i;  //静态
 4         int j;         //实例
 5         //静态方法
 6         static void Main(string[] args)
 7         {            
 8             Program.StaticMethod();  //注意,是program类的方法
 9             Program p = new Program();
10             p.InstanceMethod();      //通过实例来调用
11             Program q = new Program();
12             q.InstanceMethod();      //通过实例来调用
13 
14             Program.i = 1;
15             p.j = 2;  //  p的j 
16             q.j = 3;  //  q的j
17 ;                       
18         }
19         //实例的方法
20         static void StaticMethod()
21         {
22             i++;
23             //j++;   错误,为什么?
24         }
25         //实例的方法
26         void InstanceMethod()
27         {
28             i++;
29             j++;
30         }
31     }
32 }

注意!  在静态方法中,不能访问实例成员,所以25行的代码不能编译通过? 想想为什么?

下面举个静态成员的例子.

需求:想知道程序运行过程中,一共有多少个Animal.

在Animal类中,加入一个字段,保存Animal的数量

 public class Animal
    {   
//静态字段  animalCount
        public static int animalCount = 0;
//以下略
}

初始值为0.

然后呢,在每创造一个动物出来(构造方法)时,让animalCount 增加

 public Animal(string n, int a)
        {
           
//.....
            animalCount++;
        }
原文地址:https://www.cnblogs.com/imxh/p/2171365.html