C#面向对象中类的静态成员与非静态成员的区别

时间:2023-03-08 20:39:51
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace 静态与非静态的区别
{
public class person
{ public void M1()
{
Console.WriteLine("我是一个非静态的方法");
}
public static void M2()
{
Console.WriteLine("我是一个静态的方法");
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace 静态与非静态的区别
{
class Program
{
static void Main(string[] args)
{
person p = new person();
p.M1();//实例方法
person.M2();//静态方法
Console.ReadLine();
}
}
}

静态与非静态的区别:

1)在非静态中,既可以有实例成员,也可以有静态成员。

2)在调用实例成员的时候,需要使用    对象名.实例成员

在调用静态成员的时候,需要使用    类名。静态成员名

总结:

1)静态成员必须使用类名去调用,而实例成员使用对象名调用

2)实例函数中,既可以使用静态成员,也可以使用实例成员

3)静态函数中,只能访问静态成员,不允许访问实例成员

使用:

1)如果你想要你的类当作一个“工具类”使用,这个时候可以考虑将类写成静态的

2)静态类在整个项目中资源共享