Skip to content

JA CSharp Keyword safe

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: safe

ディレクトリ C# · 実践的な指導

更新されたメモリ安全性モデルのプレビュー修飾子: 作成者は、呼び出し元の安全でないコンテキストを必要としない宣言を明示的にマークします。

簡単な例 (Example.cs)

この例を Example.cs として別に保存し、このページの他の例とは独立して実行してください。

Example.cs:

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

この短い例は C# 14 を使用します。ここでは非対応のプレビュー構文 safe は実装していません。

構文

public static safe extern int Method();

これは C# 15 / .NET 11 のプレビューです。公式ルールでは、LangVersion=プレビューと、アプリケーションの更新されたメモリ安全性ルールの個別の有効化が必要です。現在の C# 14 はこれらの宣言をサポートしていません。

ステータス: プレビュー。現在の構成 C# 14 / .NET 10 は、これらの例をサポートしていません。

例 1: 基本形式

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

例 2: 別の実用的な形式

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

公式ソース: Microsoft Learn。

Clone this wiki locally