浅谈静态方法与非静态方法
一、静态方法
1.使用static关键字修饰的方法
访问修饰符 static 返回值类型(参数列表)
静态方法与非静态方法的简要区别
静态方法表示的类所具有的行为,而非某个具体的对象所具有的行为。
例如:学生分班这项任务,全体学生集体的事情,而非某个学生的事情。
访问级别关键字与普通方法一样,但是很少使用private,因为一般需要在类的外部访问类的静态方法。在调用静态方法时不需要实例化的对象,直接使用类来调用
二、示例

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Test 8 { 9 class CommonClass 10 { 11 public int a; 12 public void Comon_fun1(int x) 13 { 14 this.a = x; 15 Console.WriteLine("a={0}",this.a); 16 } 17 } 18 class StaticClass 19 { 20 public int a; 21 public static int b; 22 // static public int b;//也可以 23 public void fun1() 24 { 25 Console.WriteLine("fun1.非静态方法被调用"); 26 } 27 public static void fun2(int a) 28 { 29 int c;//定义非静态的局部变量 30 c= a; 31 Console.WriteLine("fun2.静态方法被调用 \n访问非静态的局部变量:c={0}\n访问静态成员变量b={1}", c,StaticClass.b); 32 CommonClass cc = new CommonClass(); 33 cc.a = a; 34 Console.WriteLine("访问外部实例非静态的成员变量:cc.a={0}", cc.a);//访问外部实例的非静态成员变量 35 cc.Comon_fun1(a);//访问外部实例的非静态方法 36 // Console.WriteLine("访问非静态的成员变量:c={0}", this.a);//无法访问非静态成员变量 37 //this.fun1();//无法访问本实例的非静态方法 38 } 39 } 40 class T 41 { 42 static void Main(string[] args) 43 { 44 StaticClass sc = new StaticClass(); 45 sc.a = 10; 46 //sc.b = 20;//错误 47 StaticClass.b = 20; 48 sc.fun1(); 49 //sc.fun2();//错误调用静态方法 50 StaticClass.fun2(40); 51 while(true); 52 } 53 } 54 }
结果
三、总结
1、C#静态方法属于类所有,类实例化前即可使用。
2、非静态方法可以访问类中的任何成员,静态方法只能访问类中的静态成员。
3、因为静态方法在类实例化前就可以使用,而类中的非静态变量必须在实例化之后才能分配内存,这样,C#静态方法调用时无法判断非静态变量使用的内存地址。所以无法使用。而静态变量的地址对类来说是固定的,故可以使用。
4、C#静态方法是一种特殊的成员方法 它不属于类的某一个具体的实例,而是属于类本身。所以对静态方法不需要首先创建一个类的实例,而是采用类名.静态方法的格式 。
5、static方法是类中的一个成员方法,属于整个类,即不用创建任何对象也可以直接调用!
static内部只能出现static变量和其他static方法!而且static方法中还不能使用this....等关键字..因为它是属于整个类!
6、静态方法效率上要比实例化高,静态方法的缺点是不自动进行销毁,而实例化的则可以做销毁。
7、静态方法和静态变量创建后始终使用同一块内存,而使用实例的方式会创建多个内存.
8、C#中的方法有两种:实例方法,静态方法.
五、补充
C#静态方法中获取类的名称
静态方法中用:
string className = System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName;
非静态方法中还可以用:
string className = this.GetType().FullName;