C#一個方法返回多個值
示例代碼:
static void Main(string[] args)
{
//聲明
int value;
string strOutValue;
//調用函數
//函數的參數有兩個返回的值
ReturnMulValue(out strOutValue,out value);
Console.WriteLine("Call ReturnMulValue(out string strOut, out int i)");
Console.WriteLine("value = {0:N}", value);//value = 1.00
Console.WriteLine("Out string value = " + strOutValue); //Out string value = out function
//調用函數 http://hovertree.com/
//函數原返回值與參數中均得到返回的值
value = ReturnMulValue(out strOutValue);
Console.WriteLine("Call ReturnMulValue(out string strOut)");
Console.WriteLine("value = {0:N}", value);//value = 2.00
Console.WriteLine("Out string value = " + strOutValue);//Out string value = out function 2
//聲明
int[] outArr;
//調用函數
//函數返回數組
ReturnMulArr(out outArr, out value);
Console.WriteLine("Call ReturnMulArr(out int[] arr, out int i)");
Console.WriteLine("value = {0:N}", value);//value = 3.00
Console.WriteLine("Out arr value ");
for (int j = 0; j < outArr.Length; j++)
{
Console.Write(outArr[j]);//12345
}
}
/// <summary>
/// 返回多個值,原函數返回空
/// </summary>
/// <param name="strOut">使用out關鍵字返回的字符串</param>
/// <param name="i">使用out關鍵字返回的數值</param>
static void ReturnMulValue(out string strOut, out int i)
{
i = 1;
strOut = "out function";
}
/// <summary>
/// 返回多個值,原函數返回數值
/// </summary>
/// <param name="strOut">使用out關鍵字返回的字符串</param>
/// <returns>原函數直接返回的數值</returns>
static int ReturnMulValue(out string strOut)
{
int i = 2;
strOut = "out function 2";
return i;
}
/// <summary>
/// 返回數組
/// </summary>
/// <param name="arr">使用out關鍵字返回的數組</param>
/// <param name="i">使用out關鍵字返回的數值</param>
static void ReturnMulArr(out int[] arr, out int i)
{
arr = new int[5] { 1, 2, 3, 4, 5};
i = 3;
}
C#中有兩種方法可以在函數中返回多個值,關鍵字是out和ref。