只读域

本文介绍如何使用C#中的readonly关键字来定义不可更改的类成员,包括实例字段和静态字段,并展示了具体的实现方式。

通过关键字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();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值