zoukankan      html  css  js  c++  java
  • readonly(C# 参考)

    readonly(C# 参考)

    readonly 关键字是可以在字段上使用的修饰符。当字段声明包括 readonly 修饰符时,该声明引入的字段赋值只能作为声明的一部分出现,或者出现在同一类的构造函数中。在此示例中,字段 year 的值无法在 ChangeYear 方法中更改,即使在类构造函数中给它赋了值。

    class Age
    {
    readonly int _year;
    Age(int year)
    {
    _year = year;
    }
    void ChangeYear()
    {
    _year = 1967; // Will not compile.
    }
    }

    只能在下列上下文中对 readonly 字段进行赋值:

    • 当在声明中初始化变量时,例如:

      public readonly int y = 5;
    • 对于实例字段,在包含字段声明的类的实例构造函数中;或者,对于静态字段,在包含字段声明的类的静态构造函数中。也只有在这些上下文中,将 readonly 字段作为 outref 参数传递才有效。

    Note注意

    readonly 关键字与 const 关键字不同。const 字段只能在该字段的声明中初始化。readonly 字段可以在声明或构造函数中初始化。因此,根据所使用的构造函数,readonly 字段可能具有不同的值。另外,const 字段为编译时常数,而 readonly 字段可用于运行时常数,如下例所示:

    Note注意

    public static readonly uint l1 = (uint)DateTime.Now.Ticks;

    // cs_readonly_keyword.cs
    // Readonly fields
    using System;
    public class ReadOnlyTest
    {
    class SampleClass
    {
    public int x;
    // Initialize a readonly field
    public readonly int y = 25;
    public readonly int z;
    public SampleClass()
    {
    // Initialize a readonly instance field
    z = 24;
    }
    public SampleClass(int p1, int p2, int p3)
    {
    x = p1;
    y = p2;
    z = p3;
    }
    }
    static void Main()
    {
    SampleClass p1 = new SampleClass(11, 21, 32);   // OK
    Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
    SampleClass p2 = new SampleClass();
    p2.x = 55;   // OK
    Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
    }
    }

    输出

    p1: x=11, y=21, z=32
    p2: x=55, y=25, z=24

    在前面的示例中,如果使用这样的语句:

    p2.y = 66; // Error

    将收到编译器错误信息:

    The left-hand side of an assignment must be an l-value

    这与试图将值赋给常数时收到的错误相同。

  • 相关阅读:
    (OK) VirtualBox 5.0.10 中 Fedora 23 在安装了增强工具后无法自动调节虚拟机分辨率的问题
    (OK) install-fedora23—gnome classic—dnf—gdm—multi-user—graphical
    (OK) fedora23——add “opening terminal” in the menu of right click
    (OK) Install Docker on Fedora 23
    (OK) 运行cBPM in Fedora23
    错误:‘bOS::SQL::SQLCommand::SQLOperation’既不是类也不是命名空间
    My enum is not a class or namespace
    【t049】&&【u001】足球
    【u002】数列排序(seqsort)
    【u003】计算概率
  • 原文地址:https://www.cnblogs.com/GeneralXU/p/1376872.html
Copyright © 2011-2022 走看看