C#基础11.1:static关键字

 

PS:注释和讲解全部在代码中

1. static关键字

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace C4_程序设计
{
    static class Land       //静态类,里面全部都是静态成员,不能实例化对象
    {
        private static string name;
        static Land()           //静态构造函数:也可以出现在非静态类中
        {                       //静态构造函数只能有一个,不能有任何访问修饰符,也不能有任何参数,也只能初始化静态字段
            name = "Hello world";
        }
        public static string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
    class Text
    {
        public int a;
        public static int b;        //静态字段存储的数据在内存中只有一份,功能/作用和C++一样
        public int A                //在还没有对象之前,静态类成员就已经存在了
        {
            get { return a; }
            set { a = value; }
        }
        public static int B         //静态属性用于对静态字段进行封装
        {                           //当然,静态属性不能用于封装非静态字段,非静态属性也不能用于封装静态字段
            get { return b; }
            set { b = value; }
        }
        /*tatic int Jud()
        {
            return a;           错误,类的静态函数中不允许出现任何非静态字段、属性、函数
        }*/
        public static int Add(Text b)
        {
            return b.a + Text.b;        //正确
        }
    }
    class static关键字
    {
        static void Main()      //主函数其实就是一个静态函数
        {
            Text me = new Text();
            me.A = 15;
            Console.WriteLine(me.a);
            Text.B = 16;            //静态字段不属于任何对象,只属于类,必须要用类名.静态字段名进行访问
            Console.WriteLine(Text.B);
            Console.WriteLine(Text.Add(me));

            Console.WriteLine(Land.Name);       //Hello world
            Land.Name = "hatucds";
            Console.WriteLine(Land.Name);       //hatucds
        }
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值