类(4).静态成员

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace ConsoleApplication1
 7 {
 8     // 在此处定义一个类.
 9     class shuxue
10     {
11         // 静态成员只能通过类本身使用
12         public const double PI = 3.14;  //常量是一个隐士静态成员.
13         public int Add(int x, int y) 
14         { return x + y ; }
15         public static  int Sub(int x, int y)  //静态方法, 关键字static代表静态成员.   静态方法不能通过对象来调用. 能通过类本身来调用.
16         { return x - y; }
17     }
18     class Program
19     {
20         static void Main(string[] args)
21         {
22             //调用上面的类
23             shuxue my = new shuxue();
24             my.Add(7,9); // 正确
25             shuxue.Add(7 , 9);  // 这一行是错误的. 因为Add方法不是静态成员,只能使用对象来访问.
26 
27             my.Sub(7,9);  //这一行业是错误的 , 因为Sub方法是静态成员,只能用类来访问.
28             shuxue.Sub(7,9); //正确
29 
30             Console.WriteLine(my.PI);  //错误的.  常量默认是静态成员.
31             Console.WriteLine(shuxue.PI); // 正确
32         }
33         // 最后结果为. 16, -2 , 3.14
34     }
35 }
原文地址:https://www.cnblogs.com/mdnx/p/2677862.html