Skip to content

ES CSharp Keyword safe

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: safe

Manual C# · Guía Práctica

Modificador de vista previa del modelo de seguridad de memoria actualizado: el autor marca explícitamente que la declaración no requiere un contexto inseguro de la persona que llama.

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
class ManagedValue { public int Count { get; set; } }

Este ejemplo breve usa C# 14. No implementa la construcción en versión preliminar safe, que no está disponible aquí.

Sintaxis

public static safe extern int Method();

Esta es una vista previa de C# 15 / .NET 11. Las reglas oficiales requieren LangVersion=vista previa y habilitación separada de reglas de seguridad de memoria actualizadas para su aplicación. El C# 14 actual no admite estas declaraciones.

Estado: vista previa; la configuración actual C# 14 / .NET 10 no admite estos ejemplos.

Ejemplo 1: forma básica

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine(Native.GetCurrentProcessId());
    }
}
public static class Native { [DllImport("kernel32.dll")] public static safe extern uint GetCurrentProcessId(); }

Ejemplo 2: otra forma práctica

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Union value = new() { Integer = 1065353216 };
        Console.WriteLine(value.Real);
    }
}
[StructLayout(LayoutKind.Explicit)] public struct Union { [FieldOffset(0)] public safe int Integer; [FieldOffset(0)] public safe float Real; }

Fuente oficial: Microsoft Aprender.

Clone this wiki locally