Skip to content

IT CSharp Keyword safe

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: safe

Manuale C# · Guida pratica

Modificatore di anteprima del modello di sicurezza della memoria aggiornato: l'autore contrassegna esplicitamente la dichiarazione come non richiedente un contesto non sicuro del chiamante.

Esempio semplice (Example.cs)

Salvare questo esempio separatamente come Example.cs. Eseguirlo indipendentemente dagli altri esempi di questa pagina.

Example.cs:

// PROJECT-EXAMPLE
class ManagedValue { public int Count { get; set; } }

Questo breve esempio usa C# 14. Non implementa il costrutto in anteprima safe, non disponibile qui.

Sintassi

public static safe extern int Method();

Questa è un'anteprima di C# 15 / .NET 11. Le regole ufficiali richiedono LangVersion=anteprima e abilitazione separata delle regole di sicurezza della memoria aggiornata per la loro applicazione. L'attuale C# 14 non supporta queste dichiarazioni.

Stato: anteprima; la configurazione corrente C# 14 / .NET 10 non supporta questi esempi.

Esempio 1: forma base

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(); }

Esempio 2: un'altra forma pratica

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; }

Fonte ufficiale: Microsoft Impara.

Clone this wiki locally