好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#类的成员之Field字段的使用

 字段是在类中声明的成员变量,用来储存描述类特征的值,字段可以被该类中声明的成员函数访问,根据字段的访问控制,也可以在其他类中通过该类或该类的实例进行访问.字段可以是任意变量类型.

字段(field)是类中最常见的成员之一。字段是在类或结构中直接声明的任意类型的变量,C#支持静态字段(类型字段)和实例字段。对于实例字段,其内存在创建实例时动态分配,而对于静态字段,其内存在类型对象创建时分配。

用readonly修饰符声明的字段为只读字段,只读字段是特殊的实例字段,它只能在字段声明中或构造函数中重新赋值,在其他任何地方都不能改变字段的值。不过,反射可以修改只读字段(没有什么是反射改不了的)。

如果类的字段没有赋值,则会自动赋默认处置,数值型为0,字符串型为空字符串。

静态字段

静态字段属于类本身,并在该类的所有实例之间共享。

只能使用类名访问静态字段,如果按实例名称访问静态字段,将出现CS0176编译时错误。

在类的外部必须采用如下方法引用静态字段:]类名.静态字段名]

实例字段

如果类中定义的字段不含有修饰符static,该字段为实例字段。

在类的外部,实例字段采用如下方法引用:]实例名.实例字段名].

例程分析

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; ? namespace 类的成员之字段 { ? ? public class Field ? ? { ? ? ? ? public static int inta;//静态字段有关键字static,一般是private属性,只能在类里访问 ? ? ? ? public readonly int intb = 1;//readonly实例字段 ? ? ? ? public int intc;//实例字段 ? ? ? ? public string str;//实例字段 ? ? } ? ? class Program ? ? { ? ? ? ? static void Main(string[] args) ? ? ? ? { ? ? ? ? ? ? Console.WriteLine("inta值是:" + Field.inta); ? ? ? ? ? ? Field.inta = 19;//静态字段赋值访问 ? ? ? ? ? ? Console.WriteLine("inta赋值后是:" + Field.inta); ? ? ? ? ? ? //Field.intb;无法读取,读取方式错误 ? ? ? ? ? ? Field a = new Field(); ? ? ? ? ? ? Console.WriteLine("intb值是:" + a.intb); ? ? ? ? ? ? //a.intb = 1;readonly实例字段是只读的,修改赋值报错 ? ? ? ? ? ? Console.WriteLine("intc值是:" + a.intc); ? ? ? ? ? ? a.intc = 100; ? ? ? ? ? ? Console.WriteLine("intc赋值后是:" + a.intc); ? ? ? ? ? ? Console.WriteLine("str数据值是:" + a.str); ? ? ? ? ? ? a.str = "123"; ? ? ? ? ? ? Console.WriteLine("str赋值后是:" + a.str); ? ? ? ? ? ? Field b = new Field(); ? ? ? ? ? ? Console.WriteLine("intc值是:" + b.intc); ? ? ? ? ? ? b.intc = 200; ? ? ? ? ? ? Console.WriteLine("intc赋值后是:" + b.intc); ? ? ? ? ? ? Console.WriteLine("intc赋值后是:" + a.intc); ? ? ? ? ? ? Console.ReadKey(); ? ? ? ? ? } ? ? } }

到此这篇关于C#类的成员之Field字段的使用的文章就介绍到这了,更多相关C# Field字段内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

查看更多关于C#类的成员之Field字段的使用的详细内容...

  阅读:44次