Skip to content

JA CSharp Keyword unsafe

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: unsafe

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

指定されたスコープでポインター構文を許可します。通常のプロジェクトをコンパイルするには、AllowUnsafeBlocks が必要です。

簡単な例 (Example.cs)

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

Example.cs:

// PROJECT-EXAMPLE
unsafe
{
    int value = 3;
    int* pointer = &value;
    *pointer = 7;
    System.Console.WriteLine(value);
}

プロジェクトで <AllowUnsafeBlocks>true</AllowUnsafeBlocks> を有効にしてください。ポインターは示されたスコープ内でのみ有効です。

結果:

7

構文

unsafe { Type* pointer = ...; }

.csprojでは、trueを設定します。マネージド データの場合は、通常、生のポインターを使用せずに Span を使用する方が簡単です。

例 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)
    {
        unsafe { int* values = stackalloc int[2]; values[0] = 3; values[1] = 7; Console.WriteLine(values[0] + values[1]); Console.WriteLine(sizeof(int)); }
    }
}

例 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)
    {
        int[] values = [2, 4, 6];
        unsafe { fixed (int* pointer = values) { pointer[1] = 9; Console.WriteLine(*(pointer + 1)); Console.WriteLine(sizeof(long)); } }
        Console.WriteLine(values[1]);
    }
}

公式ソース: Microsoft Learn。

Clone this wiki locally