欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#?輸出參數(shù)out問(wèn)題

 更新時(shí)間:2023年02月25日 08:40:39   作者:TheWindofFate  
這篇文章主要介紹了C#?輸出參數(shù)out問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

C# 輸出參數(shù)out

什么是輸出參數(shù)

方法聲明時(shí),使用out修飾符聲明的形參,成為輸出參數(shù)。

輸出參數(shù)的特點(diǎn)

1、輸出參數(shù)不創(chuàng)建新的儲(chǔ)存位置。

2、輸出參數(shù)表示的儲(chǔ)存位置就是實(shí)參表示的儲(chǔ)存位置。

3、傳遞給輸出參數(shù)的實(shí)參在方法調(diào)用前不需要強(qiáng)制初始化,在方法內(nèi)部使用該形參時(shí),需要強(qiáng)制賦值一次。

out參數(shù)的使用

使用out參數(shù),可以使方法返回多個(gè)返回值。

static void Main(string[] args)
{
   int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
   int max;
   int min;
   int sum;
   double avg;
   int[] arr = GetMaxMinSumAvg(numbers, out max, out min, out sum, out avg);
   Console.WriteLine(max);
   Console.WriteLine(min);
   Console.WriteLine(sum);
   Console.WriteLine(avg);
   Console.WriteLine(arr.Length);
   Console.ReadKey();
}
 
public static int[] GetMaxMinSumAvg(int[] nums, out int max, out int min, out int sum, out double avg)
{
   int[] res = new int[4];
   max = nums.Max();
   min = nums.Min();
   sum = nums.Sum();
   avg = nums.Average();
   return res;
}

C#中out參數(shù)、ref參數(shù)與值參數(shù)用法

ref參數(shù)是引用,out參數(shù)為輸出參數(shù)。

out參數(shù)修飾符

1、當(dāng)希望方法返回多個(gè)值時(shí),聲明 out 方法非常有用。

2、不必初始化作為 out 參數(shù)傳遞的變量。然而,必須在方法返回之前為 out 參數(shù)賦值。

3、屬性不是變量,不能作為 out 參數(shù)傳遞。

?static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? string s = "123";
? ? ? ? ? ? int result;
? ? ? ? ? ? bool b = MyTest(s,out result);
? ? ? ? }
? ? ? ? public static bool MyTest(string s, out int result)
? ? ? ? {
? ? ? ? ? ? bool isTrue;
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? result = Convert.ToInt32(s);//使用out參數(shù)必須在定義方法內(nèi)進(jìn)行賦值
? ? ? ? ? ? ? ? isTrue = true;
? ? ? ? ? ? }
? ? ? ? ? ? catch
? ? ? ? ? ? {
? ? ? ? ? ? ? ? isTrue = false;
? ? ? ? ? ? ? ? result = 0;
? ? ? ? ? ? }
? ? ? ? ? ? return isTrue;
? ? ? ? }

該方法返回類(lèi)型為bool類(lèi)型,在返回bool類(lèi)型的同時(shí)也順帶返回了int類(lèi)型的result變量。即,返回兩種變量類(lèi)型。

ref參數(shù)修飾符

1、必須使用初始化過(guò)的變量

2、屬性不是變量,不能作為 ref 參數(shù)傳遞。

3、Ref則用在要要被調(diào)出使用的方法修改調(diào)出使用者的引用的時(shí)候。

ref參數(shù)在定義的方法內(nèi)對(duì)其進(jìn)行處理,再將結(jié)果返回,定義方法無(wú)需多余的返回類(lèi)型。

?static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? //使用ref參數(shù)來(lái)交換兩個(gè)數(shù)字的值
? ? ? ? ? ? int a = 1;
? ? ? ? ? ? int b = 2;
? ? ? ? ? ? Change(ref a, ref b);
? ? ? ? ? ? Console.WriteLine("a{0},b{1}",a,b);
? ? ? ? ? ? Console.ReadKey();
? ? ? ? }
? ? ? ? public static void Change(ref int a, ref int b)
? ? ? ? {
? ? ? ? ? ? int temp;
? ? ? ? ? ? temp = a;
? ? ? ? ? ? a = b;
? ? ? ? ? ? b = temp;
? ? ? ? }

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論