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

C# 進階參數傳遞:out 關鍵字與 params 可變參數詳解

     編輯:關於C語言

out 關鍵字:專為輸出參數設計

在 C# 中,out 關鍵字與 ref 類似,都能讓方法修改參數值並在方法外部可見。但兩者有兩個關鍵差異:首先,out 參數的初始值在方法內會被忽略;其次,out 參數必須在方法內被賦值,否則編譯器會報錯。

程式碼範例

using System;

public class OutClass
{
    public static void Main(string[] args)
    {
        int total = 20;
        Console.WriteLine("Original value of 'total': {0}", total);
        Add(33, 77, out total);
        Console.WriteLine("Value after Add() call: {0}", total);
    }

    public static void Add(int i, int j, out int result)
    {
        // 編譯錯誤:無法讀取未賦值的 out 參數
        // Console.WriteLine("Initial value inside method: {0}", result);
        result = i + j; // 必須賦值
    }
}

輸出結果:

Original value of 'total': 20
Value after Add() call: 110

總結:當需要方法修改現有變數時用 ref;當方法需產生回傳值(特別是多個結果)時用 out,常搭配方法回傳值一起使用。

params 關鍵字:支援不定數量參數

透過 params 關鍵字,C# 允許方法接受可變數量的參數。參數列表可包含一般參數,但 params 參數必須置於最後,且每個方法只能有一個 params 參數,其本質是可變長度陣列。

編譯器解析規則

當編譯器嘗試解析方法呼叫時,優先尋找參數列表完全匹配的多載。若找不到,但存在合適型別的 params 版本,則會將額外參數打包成陣列並呼叫該方法。

程式碼範例

using System;

public class ParamsClass
{
    public static void Main(string[] args)
    {
        Average("List One", 5, 10, 15);
        Average("List Two", 5, 10, 15, 20, 25, 30);
    }

    public static void Average(string title, params int[] values)
    {
        int sum = 0;
        Console.Write("Average of {0}: ", title);
        for (int i = 0; i < values.Length; i++)
        {
            sum += values[i];
            Console.Write(values[i] + ", ");
        }
        Console.WriteLine(": {0}", (float)sum / values.Length);
    }
}

輸出結果:

Average of List One: 5, 10, 15, : 10
Average of List Two: 5, 10, 15, 20, 25, 30, : 17.5

提示:若需支援不同型別的不定參數,可指定 params object[] 參數。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved