Skip to content

ES CSharp Keyword partial type

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: partial es un tipo parcial

Manual C# · Guía Práctica

parcial combina múltiples declaraciones del mismo tipo en tiempo de compilación. Las piezas deben pertenecer al mismo ensamblaje y espacio de nombres y tener un nombre de tipo coherente. De esta manera puede separar datos y comportamiento entre archivos fuente; No se trata de unos pocos tipos separados.

Ejemplo sencillo (Example.cs)

Guarde este ejemplo por separado como Example.cs. Ejecútelo independientemente de los demás ejemplos de esta página.

Example.cs:

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

Resultado:

Ore

Sintaxis

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

Una clase con datos y formato en diferentes archivos.

Archivo Example.csproj:

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

</Project>

Archivo Program.cs:

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

Archivo Label.Data.cs:

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

Archivo Label.Display.cs:

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

Resultado:

Sensor #12

Estructura parcial con dimensiones y cálculo de área.

Archivo Example.csproj:

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

</Project>

Archivo Program.cs:

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

Archivo Rectangle.Size.cs:

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

Archivo Rectangle.Area.cs:

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

Resultado:

48

Fuente oficial: Microsoft Aprender.

Clone this wiki locally