标签:style blog io ar color sp on div log
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class C1 { public readonly int myvalue=1; public readonly static int value = 2; public C1() { myvalue = 3; //value = 4;//无法对静态只读字段赋值(静态构造函数或变量初始值中除外) } static C1() { //myvalue = 3;//非静态的字段、方法或属性“ConsoleApplication1.C1.myvalue”要求对象引用 value = 4; } } class Program { static void Main(string[] args) { C1 C = new C1(); Console.WriteLine("myvalue:{0}", C.myvalue); //C.myvalue = 20;//无法对只读的字段赋值(构造函数或变量初始值指定项中除外) //C1.value = 20;//无法对只读的字段赋值(构造函数或变量初始值指定项中除外) Console.WriteLine("value:{0}", C1.value); Console.ReadLine(); } } } //const字段只能在编译的时候决定,也就是说只能在字段声明的语句中初始化。而readonly字段可以在静态构造函数中完成的!
//readonly字段的值只能在字段的声明语句中和类的任何构造函数中设置
标签:style blog io ar color sp on div log
原文地址:http://www.cnblogs.com/leijiangtao/p/4133029.html