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
}
}
}