c#关键字readonly

关键点

  1. You can assign a value to a readonly field only in the following contexts:
  • When the variable is initialized in the declaration
public readonly int y = 5;
  • In an instance constructor of the class that contains the instance field declaration.
  • In the static constructor of the class that contains the static field declaration.
  1. A readonly field can’t be assigned after the constructor exits. This rule has different implications for value types and reference types:
  • Because value types directly contain their data, a field that is a readonly value type is immutable.
  • Because reference types contain a reference to their data, a field that is a readonly reference type must always refer to the same object. That object isn’t immutable. The readonly modifier prevents the field from being replaced by a different instance of the reference type. However, the modifier doesn’t prevent the instance data of the field from being modified through the read-only field.
  1. run-time constants

样例

public class SamplePoint
{
    public int x;
    // Initialize a readonly field
    public readonly int y = 25;
    public readonly int z;

    public SamplePoint()
    {
        // Initialize a readonly instance field
        z = 24;
    }

    public SamplePoint(int p1, int p2, int p3)
    {
        x = p1;
        y = p2;
        z = p3;
    }

    public static void Main()
    {
        SamplePoint p1 = new SamplePoint(11, 21, 32);   // OK
        Console.WriteLine($"p1: x={p1.x}, y={p1.y}, z={p1.z}");
        SamplePoint p2 = new SamplePoint();
        p2.x = 55;   // OK
        Console.WriteLine($"p2: x={p2.x}, y={p2.y}, z={p2.z}");
    }
    /*
     Output:
        p1: x=11, y=21, z=32
        p2: x=55, y=25, z=24
    */
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值