实例方法,即成员方法,通过实例化对象,然后通过“对象名.方法名()”调用。
静态方法,使用static关键词修饰,它是属于整个类的,不针对某个对象,
所以它通过类来调用,“类名.方法名(参数列表)”
下面写两个例子来体现实例方法与静态方法的差别
先来看看实例方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo
{
class Student
{
public void SayHello()
{
Console.WriteLine("实例方法,无static关键字");
}
}
}
调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
//想调用一个实例方法,必须实例化一个对象,然后才能调用
Student stu = new Student();
stu.SayHello();
}
}
}
再来看看静态方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo
{
class Student
{
public static void SayHello2()
{
Console.WriteLine("静态方法,有static关键字");
}
}
}
调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
//想调用静态方法,不用实例化对象,直接通过类名调用
Student.SayHello2();
}
}
}
静态成员变量的定义同样使用static关键字,如下
//静态成员变量
public static string school;
访问也通过类名访问
Student.school="蓝翔";
Console.WirteLine(Student.school.ToString());
那么,大家一定有个疑问,什么时候将类的成员定义成实例成员?什么时候定义成静态成员呢?
拿一个学生类来举例子,学生的学号、姓名都不同,所以要定义成实例成员。而他们的学校都是同一所,这是整个类共有的特点,所以要定义成静态成员。
这里有很重要的一点要说明,就是静态方法只能访问到静态成员变量,实例变量是访问不到的,也不能使用this关键字,因为this关键字表示正在操作的当前对象,静态成员不能通过对象访问。