前言
本文主要介紹了關(guān)于C#參數(shù)數(shù)組、引用參數(shù)和輸出參數(shù)的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹吧
參數(shù)數(shù)組
在C#中,可以為函數(shù)指定一個不定長的參數(shù),這個參數(shù)是函數(shù)定義中的最后一個參數(shù),這個參數(shù)叫做參數(shù)數(shù)組。
下面是一個例子:
namespace Ch6Ex2{ class Program { static int SumVals(params int[] vals) { int sum = 0; foreach (int val in vals) { sum += val; } return sum; } static void Main(string[] args) { int sum = SumVals(1, 2, 3, 4, 5); Console.WriteLine($"Summed Values = {sum}"); Console.ReadKey(); } }}
函數(shù)SumVals有一個參數(shù)數(shù)組,即vals,在定義該參數(shù)時,需要使用params參數(shù)。在調(diào)用該函數(shù)時,可以給參數(shù)輸入傳入多個實(shí)參。
使用分散式傳參時,編譯器做如下事:
1)接受實(shí)參列表,用它們在堆中創(chuàng)建并初始化一個數(shù)組。
2)把數(shù)組的引用保存到棧中的形參里。
3)如果在對應(yīng)的形參數(shù)組的位置沒有實(shí)參,編譯器會創(chuàng)建一個有零個元素的數(shù)組來使用。
4)如果數(shù)組參數(shù)是值類型,那么值被復(fù)制,實(shí)參不受方法內(nèi)部的影響。
5)如果數(shù)組參數(shù)是引用類型,那么引用被復(fù)制,實(shí)參引用的對象可以受到方法內(nèi)部的影響。
在使用數(shù)組式傳參時,編譯器使用你的數(shù)據(jù)而不是重新創(chuàng)建一個。即相當(dāng)引用參數(shù)。
引用參數(shù)
可以通過引用傳遞參數(shù),需要使用ref關(guān)鍵字。
下面是一個例子:
namespace MyProgram{ class Program { static void SwapInts (ref int a, ref int b) { int temp = b; b = a; a = temp; } static void Main(string[] args) { int a = 1; int b = 2; Console.WriteLine($"a = {a}, b = {b}"); SwapInts(ref a, ref b); Console.WriteLine($"a = {a}, b = {b}"); Console.ReadKey(); } }}
這是一個簡單的交換兩個值的程序,由于函數(shù)SwapInts使用了引用參數(shù),所以可以在函數(shù)中修改變量a和b的值,需要注意的是,在調(diào)用函數(shù)時也要使用ref傳遞引用參數(shù)。
輸出參數(shù)
輸出參數(shù)使用out關(guān)鍵字,它的效果與引用參數(shù)幾乎相同,不同點(diǎn)是:
下面是一個例子:
namespace MyProgram{ class Program { static int MaxValue (int[] intArray, out int maxIndex) { int maxValue = intArray[0]; maxIndex = 0; for (int i = 0; i < intArray.Length; i++) { if (intArray[i] > maxValue) { maxValue = intArray[i]; maxIndex = i; } } return maxValue; } static void Main(string[] args) { int maxIndex; int[] intArray = { 12, 45, 23, 77, 73 }; int maxValue = MaxValue(intArray, out maxIndex); Console.WriteLine($"maxValue = {maxValue}, maxIndex = {maxIndex}."); Console.ReadKey(); } }}
這個函數(shù)將一個數(shù)組中最大值的索引作為輸出參數(shù),返回最大值。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選