C#一个方法返回多个值
示例代码:
1 static void Main(string[] args) 2 { 3 //声明 4 int value; 5 string strOutValue; 6 7 //调用函数 8 //函数的参数有两个返回的值 9 ReturnMulValue(out strOutValue,out value); 10 11 Console.WriteLine("Call ReturnMulValue(out string strOut, out int i)"); 12 Console.WriteLine("value = {0:N}", value);//value = 1.00 13 Console.WriteLine("Out string value = " + strOutValue); //Out string value = out function 14 15 16 //调用函数 http://www.cnblogs.com/roucheng/ 17 //函数原返回值与参数中均得到返回的值 18 value = ReturnMulValue(out strOutValue); 19 20 Console.WriteLine("Call ReturnMulValue(out string strOut)"); 21 Console.WriteLine("value = {0:N}", value);//value = 2.00 22 Console.WriteLine("Out string value = " + strOutValue);//Out string value = out function 2 23 24 //声明 25 int[] outArr; 26 //调用函数 27 //函数返回数组 28 ReturnMulArr(out outArr, out value); 29 30 Console.WriteLine("Call ReturnMulArr(out int[] arr, out int i)"); 31 Console.WriteLine("value = {0:N}", value);//value = 3.00 32 Console.WriteLine("Out arr value "); 33 34 for (int j = 0; j < outArr.Length; j++) 35 { 36 Console.Write(outArr[j]);//12345 37 } 38 } 39 40 /// <summary> 41 /// 返回多个值,原函数返回空 42 /// </summary> 43 /// <param name="strOut">使用out关键字返回的字符串</param> 44 /// <param name="i">使用out关键字返回的数值</param> 45 static void ReturnMulValue(out string strOut, out int i) 46 { 47 i = 1; 48 strOut = "out function"; 49 } 50 51 /// <summary> 52 /// 返回多个值,原函数返回数值 53 /// </summary> 54 /// <param name="strOut">使用out关键字返回的字符串</param> 55 /// <returns>原函数直接返回的数值</returns> 56 static int ReturnMulValue(out string strOut) 57 { 58 int i = 2; 59 strOut = "out function 2"; 60 return i; 61 } 62 63 64 /// <summary> 65 /// 返回数组 66 /// </summary> 67 /// <param name="arr">使用out关键字返回的数组</param> 68 /// <param name="i">使用out关键字返回的数值</param> 69 static void ReturnMulArr(out int[] arr, out int i) 70 { 71 arr = new int[5] { 1, 2, 3, 4, 5}; 72 i = 3; 73 }
C#中有两种方法可以在函数中返回多个值,关键字是out和ref。