-
字段
什么是字段
为一个对象或一个类型来存储数据的,当一个对象或者类型由多个字段的时候,他们组合起来就能表达这个类型的状态
- 字段(field)是一种表示与对象或类型(类与结构体关联的变量)
- 字段是类型的成员,旧称(成员变量)
- 与对象关联的字段称为“实例字段”
- 与类型关联的字段称为“静态字段”,由static修饰 (帮助数据类型保存数据 )

- field 字段,一块田地

namespace 字段{class Program{static void Main(string[] args){/*// // 实例字段Student stu1 = new Student();// 状态:年纪大,很努力stu1.Age = 40;stu1.Score = 99;// 状态:年纪小,很贪玩Student stu2 = new Student();stu2.Age = 12;stu2.Score = 60;// //静态字段Student.ReportAmount();*///只读字段Student stu_readonly = new Student(50);Console.WriteLine($"ID初始值是{stu_readonly.ID}");// 尝试修改ID//stu_readonly.ID = 20; //这里会报错// 静态只读字段Console.WriteLine(Brush.DefaultColor.Red);Console.WriteLine(Brush.DefaultColor.Green);Console.WriteLine(Brush.DefaultColor.Blue);}}#region 实例字段&静态字段class Student{// 实例字段public readonly int ID; // readonly 只读实例字段,只能用构造器赋值public int Age;public int Score;// 静态字段public static int AverageAge;public static int AverageScore;public static int Amount;public Student(int id) //类的构造函数{Student.Amount++;//每次创建实例的时候Amount都会+1this.ID = id; // 只能在构造器里面对实例只读字段赋值,一旦设定之后就再也不能变动了}public static void ReportAmount(){Console.WriteLine($"Amount的数量为{Amount}");}}#endregion#region 静态字段的只读结构体struct Color{public int Red;public int Green;public int Blue;}class Brush{//public static readonly Color DefaultColor = new Color() { Red = 0, Green = 0, Blue = 0 }; //常规的初始化方法// 采用静态构造函数public static readonly Color DefaultColor;static Brush(){new Color() {Red = 0, Green = 0, Blue = 0};}}#endregion}
