Repository navigation
IT CSharp Keyword partial type
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
partial combina più dichiarazioni dello stesso tipo in fase di compilazione. Le parti devono appartenere allo stesso assembly e spazio dei nomi e avere un nome di tipo coerente. In questo modo puoi separare dati e comportamenti tra i file sorgente; non si tratta di alcuni tipi separati.
Salvare questo esempio separatamente come Example.cs. Eseguirlo indipendentemente dagli altri esempi di questa pagina.
Example.cs:
// PROJECT-EXAMPLE
System.Console.WriteLine(new Item().Name);
partial class Item { public string Name => GetName(); }
partial class Item { private string GetName() => "Ore"; }Risultato:
Ore
public partial class Label { }
public partial struct Rectangle { }File Example.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>File Program.cs:
using System;
internal static class Program
{
public static void Main()
{
var label = new Label { Name = "Sensor", Number = 12 };
Console.WriteLine(label.Format());
}
}File Label.Data.cs:
public partial class Label
{
public string Name { get; init; } = "";
public int Number { get; init; }
}File Label.Display.cs:
public partial class Label
{
public string Format() => $"{Name} #{Number}";
}Risultato:
Sensor #12
File Example.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>File Program.cs:
using System;
internal static class Program
{
public static void Main()
{
var size = new Rectangle { Width = 8, Height = 6 };
Console.WriteLine(size.Area);
}
}File Rectangle.Size.cs:
public partial struct Rectangle
{
public int Width { get; init; }
public int Height { get; init; }
}File Rectangle.Area.cs:
public partial struct Rectangle
{
public int Area => Width * Height;
}Risultato:
48
Fonte ufficiale: Microsoft Impara.
ClassicUO — Bad Newbie & C# Scripts IDE