iT邦幫忙

0

C# 參考呼叫Call by Reference/傳出參數Output parameter

使用return時 一次只能傳回一個值
如果需要回傳一個以上的值 那return就無法做到
參考呼叫Call by Reference/傳出參數Output parameter 可以傳出多個值

兩者的差異在於 參考呼叫Call by Reference 變數需要設定初值
而 傳出參數Output parameter 不用


參考呼叫Call by Reference

做個主控台 測試

namespace Call_by_Reference_1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b;
            a = 10;
            b = 20;
            Console.WriteLine("方法外 交換前\t a={0}  b={1}", a, b);

            CallRef(ref a, ref b);
            Console.WriteLine("離開方法後\t a={0}  b={1}", a, b);
            Console.ReadLine();
        }

        private static void CallRef(ref int x, ref int y)
        {
            Console.WriteLine("方法內 交換前\t x={0}  y={1}", x, y);
            
            int z;
            z = x;
            x = y;
            y = z;

            Console.WriteLine("方法內 交換後\t x={0}  y={1}", x, y);
        }
    }
}

結果如下
方法外 交換前 a=10 b=20
方法內 交換前 x=10 y=20
方法內 交換後 x=20 y=10
離開方法後 a=20 b=10


傳出參數Output parameter

namespace Output_parameter_1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b;

            CallOut(out a, out b);

            Console.ReadLine();
        }

        private static void CallOut(out int x, out int y)
        {
            int z;
            x = 20;
            y = 30;
            Console.WriteLine("方法內 交換前\t x={0}  y={1}", x, y);

            z = x;
            x = y;
            y = z;
            Console.WriteLine("方法內 交換後\t x={0}  y={1}", x, y);
        }
    }
}

結果如下
方法內 交換前 x=20 y=30
方法內 交換後 x=30 y=20


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
bantime
iT邦新手 5 級 ‧ 2021-03-03 21:08:07

可以使用 元組/ValueTuple

public static (int v1,int v2) GetValuePair()
{
    return (1, 2);
}
static void Main(string[] args)
{
    {
        var pair = GetValuePair();
    }
    {
        var (v1, v2) = GetValuePair();
    }
}

對也 這樣也可以回傳一個以上的值
哈 剛接觸 容器都不熟

謝謝 大大

我要留言

立即登入留言