Repository navigation
ZH TW CSharp Keyword stackalloc
Codex edited this page Oct 11, 2026
·
2 revisions
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
在目前所呼叫的堆疊上分配一個緩衝區;允許指標或跨度形式。緩衝區大小必須受到限制。
請將此範例另存為 Example.cs,並與本頁其他範例分開執行。
Example.cs:
// PROJECT-EXAMPLE
System.Span<int> values = stackalloc int[] { 2, 3 };
System.Console.WriteLine(values[0] + values[1]);結果:
5
Span<int> values = stackalloc int[3];在.csproj中,設定true。對於託管數據,通常更容易在沒有原始指標的情況下使用 Span。
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)); }
}
}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)
{
Span<int> values = stackalloc int[3];
values[0] = 2; values[1] = 4; values[2] = 8;
int sum = 0; foreach (int value in values) sum += value;
Console.WriteLine(sum);
}
}官方來源:Microsoft學習。
ClassicUO — Bad Newbie & C# Scripts IDE