#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

你可能感兴趣的:(readOnly)