Repository navigation
FR CSharp Keyword partial type
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
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.
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
public partial class Label { }
public partial struct Rectangle { }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
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.
ClassicUO — Bad Newbie & C# Scripts IDE