首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# ref 與 out 參數差異完整解析

     編輯:關於C語言

核心差異速查表

特性refout
呼叫前需初始化是否
方法內需指派值否(可選)是(強制)
用途雙向傳遞/修改單向輸出/回傳多值

程式碼示範

class TestApp
{
    // out:離開方法前必須對所有 out 參數指派值
    static void OutTest(out int x, out int y)
    {
        // int z = x; // 錯誤:x 尚未指派
        x = 1;
        y = 2;
    }

    // ref:參數需先初始化,方法內可讀可寫
    static void RefTest(ref int x, ref int y)
    {
        x = 1;
        y = x; // 可讀取 x 原值
    }

    public static void Main()
    {
        // out 範例
        int a, b;
        OutTest(out a, out b); // a=1, b=2
        Console.WriteLine($"a={a}, b={b}");

        int c = 11, d = 22;
        OutTest(out c, out d); // 原值被覆寫
        Console.WriteLine($"c={c}, d={d}");

        // ref 範例
        // int m, n; RefTest(ref m, ref n); // 編譯錯誤:未初始化
        int o = 11, p = 22;
        RefTest(ref o, ref p); // o=1, p=1
        Console.WriteLine($"o={o}, p={p}");
    }
}

進階補充

  • in (C# 7.2+):唯讀參考傳遞,結合 ref 效能與 out 安全性,適用大型結構體唯讀傳遞。
  • ref return / ref local:進階記憶體管理技巧,避免複製大型結構體。
  • 編譯器對 ref/out 參數會產生不同的 IL 元數據([Out] 屬性),影響多語言互通性。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved