C#中有两种方法可以在函数中返回多个值,关键字是out和ref。
代码示例:
[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
//调用函数 [url=http://www.cnblogs.com/roucheng/]http://www.cnblogs.com/roucheng/[/url]
//函数原返回值与参数中均得到返回的值
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;
}
|