Skip to content

ZH TW CSharp Keyword ref

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: ref

使用手冊C# · 實用指南

傳遞或傳回對變數的引用;宣告 ref local、ref field 和 ref struct。生命週期規則不允許您傳回局部變數的參考。

簡單範例 (Example.cs)

請將此範例另存為 Example.cs,並與本頁其他範例分開執行。

Example.cs:

// PROJECT-EXAMPLE
void Add(ref int value) { value += 2; }
int count = 3;
Add(ref count);
System.Console.WriteLine(count);

結果:

5

句法

Method(ref value) / ref int alias = ref value / ref struct Type

例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)
    {
        int number = 3;
        Values.Increment(ref number);
        Console.WriteLine(number);
    }
}
public static class Values { public static void Increment(ref int value) { value++; } }

例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];
        ref int first = ref Arrays.First(values);
        first = 9;
        Console.WriteLine(values[0]);
    }
}
public static class Arrays { public static ref int First(int[] values) => ref values[0]; }

範例3

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 left = 2, right = 4;
        ref int selected = ref (left > right ? ref left : ref right);
        selected += 10;
        Console.WriteLine($"{left}:{right}");
    }
}

範例4

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 number = 3;
        Reference holder = new(ref number);
        holder.Value = 9;
        Console.WriteLine(number);
    }
}
public ref struct Reference { public ref int Value; public Reference(ref int value) { Value = ref value; } }

官方來源:Microsoft學習。

Clone this wiki locally