Skip to content
标签
欢迎扫码关注公众号

C# 字段修饰符

CLR 术语C# 术语说明
Staticstatic这种字段是类型状态的一部分,而不是对象状态的一部分
Instance(默认)这种字段与类型的一个实例关联,而不是与类型本身关联
InitOnlyreadonly这种字段只能由一个构造器方法中的代码写入
Volatilevolatile编译器、CLR 和硬件不会对访问这种字段的代码执行“线程不安全”的优化措施。只有以下类型才能标记为 volatile:所有引用类型,SingleBooleanByteSByteInt16UInt16Int32UInt32Char,以及基础类型为 ByteSByteInt16UInt16Int32UInt32 的所有枚举类型。

下面是一段各种字段类型的实例代码:

csharp
class SomeType
{
    // 这是一个静态 readonly 字段,在运行时对这个类进行初始化时,它的值会被计算并存储到内存中
    public static readonly Random s_random = new Random();

    // 这是一个静态 read/write 字段
    private static Int32 s_numberOfWrites = 0;

    // 这是一个实例 readonly 字段
    public readonly String Pathname = "Untitled";

    // 这是一个实例 read/write 字段
    private System.IO.FileStream m_fs;

    public SomeType(string pathname)
    {
        this.Pathname = pathname;
    }

    private string DoSomething()
    {
        // 读写静态字段
        s_numberOfWrites = s_numberOfWrites + 1;

        // 读取 readonly 字段
        return Pathname;
    }
}

重要提示:当某个字段是引用类型,并且该字段被标记为 readonly 时,不可改变的是引用,而非字段的引用对象。

以下代码对此进行了演示:

csharp
public sealed class AType
{
    public static readonly Char InvalidChars = new Char { 'A', 'B', 'C' };
}

public sealed class AnotherType
{
    public static void M()
    {
        // 下面三行代码是合法的,可通过编译,并可成功
        // 修改 InvalidChars 数组中的字符
        AType.InvalidChars[0] = 'X';
        AType.InvalidChars[1] = 'Y';
        AType.InvalidChars[2] = 'Z';

        // 下一行代码是非法的,无法通过编译,
        // 因为不能让 InvalidChars 引用别的什么东西
        AType.InvalidChars = new Char { 'X', 'Y', 'Z' };
    }
}

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.