Skip to content

DE CSharp Keyword partial type

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: partial ist ein Teiltyp

Handbuch C# · Praktischer Leitfaden

Partial kombiniert mehrere Deklarationen desselben Typs zur Kompilierungszeit. Die Teile müssen zur gleichen Baugruppe und zum gleichen Namensraum gehören und einen einheitlichen Typnamen haben. Auf diese Weise können Sie Daten und Verhalten zwischen Quelldateien trennen; es handelt sich nicht um ein paar einzelne Typen.

Einfaches Beispiel (Example.cs)

Speichern Sie dieses Beispiel separat als Example.cs. Führen Sie es unabhängig von den anderen Beispielen dieser Seite aus.

Example.cs:

// PROJECT-EXAMPLE
System.Console.WriteLine(new Item().Name);
partial class Item { public string Name => GetName(); }
partial class Item { private string GetName() => "Ore"; }

Ergebnis:

Ore

Syntax

public partial class Label { }
public partial struct Rectangle { }

Eine Klasse mit Daten und Formatierungen in verschiedenen Dateien

Datei Example.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>14.0</LangVersion>
    <Nullable>enable</Nullable>
    
  </PropertyGroup>

</Project>

Datei Program.cs:

using System;
internal static class Program
{
    public static void Main()
    {
        var label = new Label { Name = "Sensor", Number = 12 };
        Console.WriteLine(label.Format());
    }
}

Datei Label.Data.cs:

public partial class Label
{
    public string Name { get; init; } = "";
    public int Number { get; init; }
}

Datei Label.Display.cs:

public partial class Label
{
    public string Format() => $"{Name} #{Number}";
}

Ergebnis:

Sensor #12

Teilstruktur mit Abmessungen und Flächenberechnung

Datei Example.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>14.0</LangVersion>
    <Nullable>enable</Nullable>
    
  </PropertyGroup>

</Project>

Datei Program.cs:

using System;
internal static class Program
{
    public static void Main()
    {
        var size = new Rectangle { Width = 8, Height = 6 };
        Console.WriteLine(size.Area);
    }
}

Datei Rectangle.Size.cs:

public partial struct Rectangle
{
    public int Width { get; init; }
    public int Height { get; init; }
}

Datei Rectangle.Area.cs:

public partial struct Rectangle
{
    public int Area => Width * Height;
}

Ergebnis:

48

Offizielle Quelle: Microsoft Learn.

Clone this wiki locally