现在的位置: 首页 > 综合 > 正文

C#.NET中的函数的输出参数(关键字out)

2013年06月07日 ⁄ 综合 ⁄ 共 837字 ⁄ 字号 评论关闭
/*
 * Created by SharpDevelop.
 * User: noo
 * Date: 2009-8-16
 * Time: 13:42
 * 
 * 函数的输出参数(关键字out)
 
*/
using System ;
class A
{
    
public static int Max(int[] intArray,out int maxIndex)//函数的功能是返回数组中的最大值,maxIndex是最大值的下标
    {
        
int maxVal=intArray[0];
        maxIndex
=0;// 控制离开当前方法之前必须对 out 参数“maxIndex”赋值
        for(int i=1;i<intArray.Length ;i++)
        {
            
if(intArray[i]>maxVal)
            {
                maxVal
=intArray[i];
                maxIndex
=i;
            }
        }
        
return maxVal;
    }
}
//out同ref参数一样,也会改变参数的值,可以把未赋值的变量用作out参数
class Test
{
    
static void Main()
    {
        
int[] myArray={1,5,3,6,3,8,0,9,4,5,};
        
int index;
        
int maxValue=A.Max (myArray,out index);//这里调用并不需要为out参数赋值
        Console.WriteLine ("该数组的最大值是:{0}",maxValue);//9
        Console.WriteLine ("最大值是数组中第{0}个元素",index+1);//第8个元素
    }
}

抱歉!评论已关闭.