C # language has a lot to learn, here we mainly introduce C # static fields and C # instance fields, including the introduction of the ReadOnly keyword is used to fame a read-only field.
C # static fields and C # instance fields
Fields have C # static fields and C # instance fields two, which are reference-passing and can be of any type.
Cases:
private static int i = 0; //声名一个静态字段
private int j = 0; //声名一个实例字段
static void Main(string[] args)
{
Program a = new Program();//建立对像引用,并实例化。
Console.WriteLine(a.j);//用对像来访问字段j
Console.WriteLine(Program.i);//静态字段需要用类名来访问
}
As we can see from the example, the static field belongs to the class, and the instance field belongs to the object.
ReadOnly Key Words:
The ReadOnly keyword is used to name a read-only field, which means that the field is not allowed to be overwritten, except that, in a constructor, a read-only field can be overwritten.
Cases:
class Program
{
private readonly int i = 0;//声名一个只读字段
private readonly int j = 0;
Program()
{
this.j = 10;//构造函数中对字段j进行改写
}
static void Main(string[] args)
{
Program a = new Program();//建立对像引用,并实例化。
//a.i = 10;//这里是会报错的
Console.WriteLine(a.j);
Console.WriteLine(a.i);
}
}