Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# readonly

作者:饮尽孤单   发布日期:2025-03-26   浏览:103

// 使用 readonly 关键字的示例

public class Example
{
    // readonly 字段只能在声明时或构造函数中初始化
    private readonly int readOnlyField;

    // 构造函数
    public Example(int value)
    {
        // 可以在构造函数中初始化 readonly 字段
        readOnlyField = value;
    }

    // 尝试在方法中修改 readonly 字段会报错
    public void TryModifyReadOnlyField()
    {
        // 下面这行代码会导致编译错误
        // readOnlyField = 10;
    }

    // 可以创建只读属性
    public int ReadOnlyProperty { get; } = 5;

    // 只读自动实现属性(C# 6.0 及以上版本)
    public string ReadOnlyAutoProperty { get; } = "Initial Value";
}

// 使用示例
public class Program
{
    public static void Main()
    {
        Example example = new Example(42);
        Console.WriteLine($"ReadOnlyField: {example.readOnlyField}");
        Console.WriteLine($"ReadOnlyProperty: {example.ReadOnlyProperty}");
        Console.WriteLine($"ReadOnlyAutoProperty: {example.ReadOnlyAutoProperty}");
    }
}

解释说明:

  • readonly 关键字用于声明一个字段,该字段只能在声明时或构造函数中进行赋值。一旦赋值后,在类的其他地方不能再修改它的值。
  • 在上面的代码中,readOnlyField 是一个 readonly 字段,它只能在构造函数中被赋值。
  • ReadOnlyPropertyReadOnlyAutoProperty 是只读属性,它们只能通过构造函数或声明时进行初始化,之后不能修改。
  • 如果尝试在方法中修改 readonly 字段,编译器会报错。

上一篇:c# int

下一篇:c# async await

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站