ZH TW CSharp Keyword closed - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki

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

C#: closed

使用手冊C# · 實用指南

封閉層次結構預覽修改器:直接後代必須屬於同一組件。編譯器可以透過此類後代分析開關的完整性。

簡單範例 (Example.cs)

請將此範例另存為 Example.cs,並與本頁其他範例分開執行。

Example.cs:

// PROJECT-EXAMPLE
sealed class Finished { }

此簡短範例使用 C# 14,並未實作此處不支援的預覽語法 closed。

句法

public closed class Base { ... }

官方目录指的是C#15。目前的C#14 / .NET10不接受這些範例:需要相容的預覽編譯器和對應的執行時間平台。這是對未來功能的概述,而不是支援啟用命令。

**狀態:預覽;目前配置 C# 14 / .NET 10 不支援這些範例。 **

例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)
    {
        Status status = new Ready();
        Console.WriteLine(status switch { Ready => "ready", Busy => "busy" });
    }
}
public closed record Status;
public sealed record Ready : Status;
public sealed record Busy : Status;

例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)
    {
        Shape shape = new Circle(3);
        Console.WriteLine(shape switch { Circle(var radius) => radius * radius, Box(var width) => width * width });
    }
}
public closed record Shape;
public sealed record Circle(int Radius) : Shape;
public sealed record Box(int Width) : Shape;

官方來源:Microsoft學習。