Skip to content

FR CSharp Keyword partial type

Codex edited this page Oct 11, 2026 · 2 revisions

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

C# : partial est un type partiel

Manuel C# · Guide pratique

partial combine plusieurs déclarations du même type au moment de la compilation. Les pièces doivent appartenir au même assembly et au même espace de noms et avoir un nom de type cohérent. De cette façon, vous pouvez séparer les données et le comportement entre les fichiers sources ; il ne s'agit pas de quelques types distincts.

Exemple simple (Example.cs)

Enregistrez cet exemple séparément dans Example.cs. Exécutez-le indépendamment des autres exemples de cette page.

Example.cs:

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

Résultat:

Ore

Syntaxe

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

Une classe avec des données et un formatage dans différents fichiers

Fichier Example.csproj :

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

</Project>

Fichier Program.cs :

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

Fichier Label.Data.cs :

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

Fichier Label.Display.cs :

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

Résultat:

Sensor #12

Structure partielle avec dimensions et calcul de surface

Fichier Example.csproj :

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

</Project>

Fichier Program.cs :

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

Fichier Rectangle.Size.cs :

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

Fichier Rectangle.Area.cs :

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

Résultat:

48

Source officielle : Microsoft Apprendre.

Clone this wiki locally