Skip to content

JA CSharp Keyword field

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: field

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

アクセサー内で自動的に生成されたプロパティ フィールドを参照します。自動ストレージと検証を組み合わせることができます。

簡単な例 (Example.cs)

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

Example.cs:

// PROJECT-EXAMPLE
var item = new Item();
item.Count = -2;
System.Console.WriteLine(item.Count);
class Item { public int Count { get; set => field = System.Math.Max(0, value); } }

結果:

0

構文

public int Count { get; set => field = Math.Max(0, value); }

構文 C# 14。 @field 識別子は、同じ名前を持つ独自のメンバーを参照できます。

例 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)
    {
        Meter meter = new() { Count = -3 };
        Console.WriteLine(meter.Count);
    }
}
public class Meter { public int Count { get; set => field = Math.Max(0, value); } }

例 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)
    {
        Profile profile = new() { Name = " archer " };
        Console.WriteLine(profile.Name);
    }
}
public class Profile { public string Name { get => field ?? ""; set => field = value.Trim(); } }

公式ソース: Microsoft Learn。

Clone this wiki locally