C#?輸出參數(shù)out問題
C# 輸出參數(shù)out
什么是輸出參數(shù)
方法聲明時,使用out修飾符聲明的形參,成為輸出參數(shù)。
輸出參數(shù)的特點
1、輸出參數(shù)不創(chuàng)建新的儲存位置。
2、輸出參數(shù)表示的儲存位置就是實參表示的儲存位置。
3、傳遞給輸出參數(shù)的實參在方法調(diào)用前不需要強制初始化,在方法內(nèi)部使用該形參時,需要強制賦值一次。
out參數(shù)的使用
使用out參數(shù),可以使方法返回多個返回值。
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、當希望方法返回多個值時,聲明 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)進行賦值 ? ? ? ? ? ? ? ? isTrue = true; ? ? ? ? ? ? } ? ? ? ? ? ? catch ? ? ? ? ? ? { ? ? ? ? ? ? ? ? isTrue = false; ? ? ? ? ? ? ? ? result = 0; ? ? ? ? ? ? } ? ? ? ? ? ? return isTrue; ? ? ? ? }
該方法返回類型為bool類型,在返回bool類型的同時也順帶返回了int類型的result變量。即,返回兩種變量類型。
ref參數(shù)修飾符
1、必須使用初始化過的變量
2、屬性不是變量,不能作為 ref 參數(shù)傳遞。
3、Ref則用在要要被調(diào)出使用的方法修改調(diào)出使用者的引用的時候。
ref參數(shù)在定義的方法內(nèi)對其進行處理,再將結果返回,定義方法無需多余的返回類型。
?static void Main(string[] args) ? ? ? ? { ? ? ? ? ? ? //使用ref參數(shù)來交換兩個數(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; ? ? ? ? }
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
WPF自定義控件實現(xiàn)ItemsControl魚眼效果
這篇文章主要為大家詳細介紹了WPF如何通過自定義控件實現(xiàn)ItemsControl魚眼效果,文中的示例代碼講解詳細,需要的可以參考一下2024-01-01C#實現(xiàn)圖片上傳(PC端和APP)保存及 跨域上傳說明
這篇文章主要介紹了C#實現(xiàn)圖片上傳(PC端和APP)保存及 跨域上傳說明的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-12-12