C # static field and instance field analysis

Source: Internet
Author: User

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);
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.