- 字段历史悠久,C 语言就有了
ID、Name 各占一块空间,这也是字段称为 field 的由来
什么是字段
示例:实例字段与静态字段class Program
{
static void Main(string[] args)
{
List<Student> stuList = new List<Student>();
for (int i = 0; i < 100; i++)
{
Student stu = new Student();
stu.Age = 24;
stu.Score = i;
stuList.Add(stu);
}
int totalAge = 0;
int totalScore = 0;
foreach (var stu in stuList)
{
totalAge += stu.Age;
totalScore += stu.Score;
}
Student.AverageAge = totalAge / Student.Amount;
Student.AverageScore = totalScore / Student.Amount;
Student.ReportAmount();
Student.ReportAverageAge();
Student.ReportAverageScore();
}
}
class Student
{
public int Age;
public int Score;
public static int AverageAge;
public static int AverageScore;
public static int Amount;
public Student()
{
Student.Amount++;
}
public static void ReportAmount()
{
Console.WriteLine(Student.Amount);
}
public static void ReportAverageAge()
{
Console.WriteLine(Student.AverageAge);
}
public static void ReportAverageScore()
{
Console.WriteLine(Student.AverageScore);
}
}
字段的声明
字段(field)是一种表示与对象或类关联的变量的成员。
- 对于实例字段,它初始化的时机是在实例创建时
- 声明实例字段时初始化值与在实例构造器里面初识化实例字段是一样的
- 对于静态字段,它初始化的时机是在运行环境加载该数据类型时
- 即静态构造器初始化时
- 声明静态字段时设置初始化值与在静态构造器里面初始化静态字段其实是一样的
数据类型被运行环境加载时,它的静态构造器将会被调用,且只被调用一次。
静态构造器:
只读字段
只读字段为实例或类型保存一旦初始化后就不希望再改变的值。
Code Shippet
ctor + 2 * TAB:插入构造函数代码片段。
只读实例字段
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student(1);
Console.WriteLine(stu1.ID);
}
}
class Student
{
public readonly int ID;
public Student(int id)
{
this.ID = id;
}
}
只读静态字段
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Brush.DefaultColor.Red);
Console.WriteLine(Brush.DefaultColor.Green);
Console.WriteLine(Brush.DefaultColor.Blue);
}
}
struct Color
{
public int Red;
public int Green;
public int Blue;
}
class Brush
{
public static readonly Color DefaultColor;
static Brush()
{
Brush.DefaultColor = new Color() { Red = 0, Green = 0, Blue = 0 };
}
}