Repository navigation
ZH TW CSharp Keyword partial type
Codex edited this page Oct 11, 2026
·
2 revisions
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
partial 在編譯時組合多個相同類型的聲明。這些部分必須屬於相同的程序集和命名空間,並且具有一致的類型名稱。透過這種方式,您可以分離來源檔案之間的資料和行為;它不是幾種單獨的類型。
請將此範例另存為 Example.cs,並與本頁其他範例分開執行。
Example.cs:
// PROJECT-EXAMPLE
System.Console.WriteLine(new Item().Name);
partial class Item { public string Name => GetName(); }
partial class Item { private string GetName() => "Ore"; }結果:
Ore
public partial class Label { }
public partial struct Rectangle { }文件Example.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>文件Program.cs:
using System;
internal static class Program
{
public static void Main()
{
var label = new Label { Name = "Sensor", Number = 12 };
Console.WriteLine(label.Format());
}
}文件Label.Data.cs:
public partial class Label
{
public string Name { get; init; } = "";
public int Number { get; init; }
}文件Label.Display.cs:
public partial class Label
{
public string Format() => $"{Name} #{Number}";
}結果:
Sensor #12
文件Example.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>文件Program.cs:
using System;
internal static class Program
{
public static void Main()
{
var size = new Rectangle { Width = 8, Height = 6 };
Console.WriteLine(size.Area);
}
}文件Rectangle.Size.cs:
public partial struct Rectangle
{
public int Width { get; init; }
public int Height { get; init; }
}文件Rectangle.Area.cs:
public partial struct Rectangle
{
public int Area => Width * Height;
}結果:
48
官方來源:Microsoft學習。
ClassicUO — Bad Newbie & C# Scripts IDE