首页 > 其他 > 详细

C# readonly const

时间:2014-03-12 16:44:57      阅读:356      评论:0      收藏:0      [点我收藏+]

readonly关键字是可以在字段上使用的修饰符。当字段声明包括 readonly 修饰符时,该声明引入的字段赋值只能作为声明的一部分出现,或者出现在同一类的构造函数中

 

在此示例中,字段 year 的值无法在 ChangeYear 方法中更改,即使在类构造函数中给它赋了值。

bubuko.com,布布扣
 1     class Age
 2     {
 3         readonly int _year;
 4         Age(int year)
 5         {
 6             _year = year;
 7         }
 8         void ChangeYear()
 9         {
10             //_year = 1967; // Compile error if uncommented.
11         }
12     }
bubuko.com,布布扣
  • 只能当在声明中初始化变量时,例如:
public readonly int y = 5;
  • 或对于实例字段,在包含字段声明的类的实例构造函数中;或对于静态字段,在包含字段声明的类的静态构造函数中。  也只有在这些上下文中,将 readonly 字段作为 out 或 ref 参数传递才有效。
bubuko.com,布布扣
 1     public class ReadOnlyTest
 2     {
 3        class SampleClass
 4        {
 5           public int x;
 6           // Initialize a readonly field
 7           public readonly int y = 25;
 8           public readonly int z;
 9 
10           public SampleClass()
11           {
12              // Initialize a readonly instance field
13              z = 24;
14           }
15 
16           public SampleClass(int p1, int p2, int p3)
17           {
18              x = p1;
19              y = p2;
20              z = p3;
21           }
22        }
23 
24        static void Main()
25        {
26           SampleClass p1 = new SampleClass(11, 21, 32);   // OK
27           Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
28           SampleClass p2 = new SampleClass();
29           p2.x = 55;   // OK
30           Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
31        }
32     }
33     /*
34      Output:
35         p1: x=11, y=21, z=32
36         p2: x=55, y=25, z=24
37     */
bubuko.com,布布扣

在前面的示例中,如果使用这样的语句:

p2.y = 66;        // Error

将收到编译器错误信息:

The left-hand side of an assignment must be an l-value

这与尝试将值赋给常数时收到的错误相同。

 

readonly 关键字与 const 关键字不同。const  字段只能在该字段的声明中初始化。readonly 字段可以在声明或构造函数中初始化。因此,根据所使用的构造函数,readonly 字段可能具有不同的值。另外,const 字段为编译时常数,而 readonly 字段可用于运行时常数,如下例所示:

public static readonly uint timeStamp = (uint)DateTime.Now.Ticks;

 

Reference: http://msdn.microsoft.com/zh-cn/library/acdd6hb7.aspx

 

Additional:

The modifier readonly means that the value cannot be assigned except in the declaration or constructor. It does not mean that the assigned object becomes immutable(不可变)。

1 public static class MyList
2 {
3     public static readonly SortedList<int, List<myObj>> CharList;
4     // ...etc.
5 }

But even using readonly, you can still add items to the list from another class.

MyList.CharList[100] = new List<myObj>() { new myObj(30, 30) };
//or
MyList.CharList.Add(new List<myObj>() { new myObj(30, 30) });

C# readonly const,布布扣,bubuko.com

C# readonly const

原文:http://www.cnblogs.com/wxin/p/3596385.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!