C#类中静态资源和非静态资源

1.类的组成:

类组成;静态的属性(变量)和动态的行为(方法),变量分为静态变量和非静态变量,方法分为静态变量和非静态方法,其中静态变量和静态方法使用static关键字进行修饰.

a.在类中使用static关键字修饰的资源,称为类资源,变量称为类变量,方法称为类方法,可以通过类名直接访问

b.没有static修饰的资源,称为实例资源,访问形式必须通过对象名的形式,进行调用。

internal class student
{
    public string name { get; set; }
    public int age { get; set; }
    public static int score = 100;//创建静态资源
}

在主函数中进行调用:
staic void main()
{
            student.score = 0;
            student s=new student(); //静态资源可以通过类名直接进行调用
            s.name = "张三";          //非静态资源必须通过实例化对象进行调用
}

c.类资源,不属于任何对象,他在同一个类产生的对象之间进行共享,实例资源,与对象绑定,属于实例对象独享资源

d.实例方法,可以直接调用静态资源,单在静态方法中,只能调用静态资源,无法直接使用非静态资源

internal class Program
{
    public int a;
    public int b;
    public static int c;
    public void A() { C();}//非静态方法可以调用,静态资源不报错
    public void B() { }
    static void C() { B();}//静态资源,无法调用非静态资源,报错无法直接调用

    static void Main(string[] args)
    {

        /*资源调用*/

        A();//调用出错,Main是静态方法,无法调用实例化资源
        C();//不报错,  可以正常调用

        
        //调用实例化资源必须实例化对象
        Program  p=new Program();
        p.A();//不报错
}

e.内存分配不同,静态资源在内存中是唯一的,而实例资源在内存中,创建几次对象,就会分配多少次内存空间

二.静态资源实例化应用

统计学校报到学生和学生数目,输出学校名称:

internal class student
{
    public string name; /*对象资源
    public int Score;
    public int Chinese;
    public int math;  
    public int English;

     //静态资源:类资源
   public static string shcool = "清华大学";
   public static int count = 0;
   public Student() { count++; } //构造方法


}

在主函数中进行调用:
static void main()
{
  Student S3 = new Student() { name = "王五", math = 90, Chinese = 85,English=92};
  Student S4 = new Student() { name = "麻子", math = 50, Chinese = 60, English = 70 };
  Student S5 = new Student() { name = "瓜子", math = 10, Chinese = 20, English = 30 };
  Console.WriteLine($"studentcoutn={Student.count},Student.school");
}

输出结果:

学生数量:3,学校:清华大学

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值