• 四种成员都是用来表达数据的

    字段

    什么是字段

  • 为一个对象或一个类型来存储数据的,当一个对象或者类型由多个字段的时候,他们组合起来就能表达这个类型的状态

  • 字段(field)是一种表示与对象或类型(类与结构体关联的变量)
  • 字段是类型的成员,旧称(成员变量)
  • 与对象关联的字段称为“实例字段”
  • 与类型关联的字段称为“静态字段”,由static修饰 (帮助数据类型保存数据 )

image.png

  • field 字段,一块田地

image.png

  1. namespace 字段
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. /*
  8. // // 实例字段
  9. Student stu1 = new Student();
  10. // 状态:年纪大,很努力
  11. stu1.Age = 40;
  12. stu1.Score = 99;
  13. // 状态:年纪小,很贪玩
  14. Student stu2 = new Student();
  15. stu2.Age = 12;
  16. stu2.Score = 60;
  17. // //静态字段
  18. Student.ReportAmount();
  19. */
  20. //只读字段
  21. Student stu_readonly = new Student(50);
  22. Console.WriteLine($"ID初始值是{stu_readonly.ID}");
  23. // 尝试修改ID
  24. //stu_readonly.ID = 20; //这里会报错
  25. // 静态只读字段
  26. Console.WriteLine(Brush.DefaultColor.Red);
  27. Console.WriteLine(Brush.DefaultColor.Green);
  28. Console.WriteLine(Brush.DefaultColor.Blue);
  29. }
  30. }
  31. #region 实例字段&静态字段
  32. class Student
  33. {
  34. // 实例字段
  35. public readonly int ID; // readonly 只读实例字段,只能用构造器赋值
  36. public int Age;
  37. public int Score;
  38. // 静态字段
  39. public static int AverageAge;
  40. public static int AverageScore;
  41. public static int Amount;
  42. public Student(int id) //类的构造函数
  43. {
  44. Student.Amount++;//每次创建实例的时候Amount都会+1
  45. this.ID = id; // 只能在构造器里面对实例只读字段赋值,一旦设定之后就再也不能变动了
  46. }
  47. public static void ReportAmount()
  48. {
  49. Console.WriteLine($"Amount的数量为{Amount}");
  50. }
  51. }
  52. #endregion
  53. #region 静态字段的只读结构体
  54. struct Color
  55. {
  56. public int Red;
  57. public int Green;
  58. public int Blue;
  59. }
  60. class Brush
  61. {
  62. //public static readonly Color DefaultColor = new Color() { Red = 0, Green = 0, Blue = 0 }; //常规的初始化方法
  63. // 采用静态构造函数
  64. public static readonly Color DefaultColor;
  65. static Brush()
  66. {
  67. new Color() {Red = 0, Green = 0, Blue = 0};
  68. }
  69. }
  70. #endregion
  71. }