JA CSharp Keyword struct - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
C#: struct
値 type を宣言: 代入により値がコピーされます。小さな不変構造は、座標と結果に便利です。
簡単な例 (Example.cs)
この例を Example.cs として別に保存し、このページの他の例とは独立して実行してください。
Example.cs:
// PROJECT-EXAMPLE
Point original = new() { X = 2 };
Point copy = original;
copy.X = 9;
System.Console.WriteLine($"{original.X}:{copy.X}");
struct Point { public int X; }
結果:
2:9
構文
struct Name { ... } / readonly struct Name { ... }
例 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)
{
Point first = new(2, 3);
Point copy = first;
copy.X = 9;
Console.WriteLine($"{first.X}:{copy.X}");
}
}
public struct Point(int x, int y) { public int X = x; public int Y = y; }
例 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, 4);
Console.WriteLine(position.X + position.Y);
}
}
public readonly struct Position(int x, int y) { public int X { get; } = x; public int Y { get; } = y; }
公式ソース: Microsoft Learn。