【转载】#336 - Declaring and Using a readonly Field

You can make a field in a class read-only by using the readonly modifier when the field is declared.

In the example below, code that creates or uses instances of the Dog class will be able to read the SerialNumber field, but not write to it.

 1 public class Dog
 2 {
 3     public string Name;
 4     public int Age;
 5     public readonly string SerialNumber;
 6 
 7     public Dog(string name, int age, string serNumber)
 8     {
 9         Name = name;
10         Age = age;
11         SerialNumber = serNumber;
12     }
13 }    

You can assign a value to a readonly field in only two different places:

  • In the class constructor
  • As part of the field's declartion
1 public readonly string BestFriend = "Man";

 原文地址:#336 - Declaring and Using a readonly Field

posted on 2014-03-11 19:37  yuthreestone  阅读(171)  评论(0编辑  收藏  举报

导航