Skip to content

KO 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 학습.

Clone this wiki locally