- 什么是字段
- 字段(field)是一种表示与对象或类型(类与结构体)关联的变量
- 字段是类型的成员,旧称“成员变量”
- 与对象关联的字段亦称“实例字段”
- 与类型关联的字段称为“静态字段”,由static修饰
- 字段的声明
- 参见C#语言定义文档
- 尽管字段声明带有分号,但它不是语句
- 字段的名字一定是名词
- 字段的初始值
- 无显示初始化时,字段获得其类型的默认值,所以字段“永远都不会未被初始化”
- 实例字段初始化的时机——对象创建时
- 静态字段初始化的时机——类型被加载(load)时
- 只读字段
- 实例只读字段
- 静态只读字段
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);
}
}
只读字段:为实例或者类型保存一旦初始化后,就不希望再改变的值。
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student(1);
Console.WriteLine(stu1.ID);
//stu1.ID = 2 报错
}
}
class Student
{
public readonly int ID; //只读实例字段
public int Age;
public int Score;
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);
//Brush.DefaultColor = new Color() { Red = 255, Green = 255, Blue = 255 };
//会报错。只能初始化,初始化后不能再被赋值
}
}
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 };
//初始化
}
}