日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#?輸出參數out問題_C#教程

作者:TheWindofFate ? 更新時間: 2023-06-17 編程語言

C# 輸出參數out

什么是輸出參數

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

輸出參數的特點

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

2、輸出參數表示的儲存位置就是實參表示的儲存位置。

3、傳遞給輸出參數的實參在方法調用前不需要強制初始化,在方法內部使用該形參時,需要強制賦值一次。

out參數的使用

使用out參數,可以使方法返回多個返回值。

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參數、ref參數與值參數用法

ref參數是引用,out參數為輸出參數。

out參數修飾符

1、當希望方法返回多個值時,聲明 out 方法非常有用。

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

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

?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參數必須在定義方法內進行賦值
? ? ? ? ? ? ? ? isTrue = true;
? ? ? ? ? ? }
? ? ? ? ? ? catch
? ? ? ? ? ? {
? ? ? ? ? ? ? ? isTrue = false;
? ? ? ? ? ? ? ? result = 0;
? ? ? ? ? ? }
? ? ? ? ? ? return isTrue;
? ? ? ? }

該方法返回類型為bool類型,在返回bool類型的同時也順帶返回了int類型的result變量。即,返回兩種變量類型。

ref參數修飾符

1、必須使用初始化過的變量

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

3、Ref則用在要要被調出使用的方法修改調出使用者的引用的時候。

ref參數在定義的方法內對其進行處理,再將結果返回,定義方法無需多余的返回類型。

?static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? //使用ref參數來交換兩個數字的值
? ? ? ? ? ? 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;
? ? ? ? }

總結

原文鏈接:https://blog.csdn.net/TheWindofFate/article/details/122621673

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新