Skip to content

JA CSharp Keyword readonly

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: readonly

ディレクトリ C# · 実践的な指導

初期化またはコンストラクター後のフィールド置換を禁止します。不変構造と読み取り専用参照アクセスについても説明します。

簡単な例 (Example.cs)

この例を Example.cs として別に保存し、このページの他の例とは独立して実行してください。

Example.cs:

// PROJECT-EXAMPLE
System.Console.WriteLine(new Item(7).Count);
class Item { public readonly int Count; public Item(int count) { Count = count; } }

結果:

7

構文

readonly Type field; / readonly struct Type / ref readonly Type

リストへの読み取り専用参照は、リストの要素を不変にしません。 const の場合、値はコンパイル時にわかっている必要があります。

例 1: 基本形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Settings settings = new("profile");
        Console.WriteLine(settings.Name);
    }
}
public class Settings(string name) { public readonly string Name = name; }

例 2: 別の実用的な形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Position position = new(2, 3);
        Console.WriteLine(position.Sum);
    }
}
public readonly struct Position(int x, int y) { public int X { get; } = x; public int Y { get; } = y; public int Sum => X + Y; }

公式ソース: Microsoft Learn。

Clone this wiki locally