孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

通过关键字readonly可以设定类中的只读域,即不能修改此域:

/*
  Example6_3.cs illustrates the use of readonly fields
*/


// declare the Car class
public class Car
{

    // declare a readonly field
    public readonly string make;

    // declare a static readonly field
    public static readonly int wheels = 4;

    // define a constructor
    public Car(string make)
    {
        System.Console.WriteLine("Creating a Car object");
        this.make = make;
    }

}


class Example6_3
{

    public static void Main()
    {

        System.Console.WriteLine("Car.wheels = " + Car.wheels);
        // Car.wheels = 5;  // causes compilation error

        // create a Car object
        Car myCar = new Car("Toyota");

        System.Console.WriteLine("myCar.make = " + myCar.make);
        // myCar.make = "Porsche";  // causes compilation error
        string i = System.Console.ReadLine();
    }

}

posted on 2011-05-03 20:32  孤独的猫  阅读(161)  评论(0编辑  收藏  举报