C#中out参数、ref参数与值参数的用法及区别

2020-01-05 09:26:12王冬梅
函数,获取数组中最大值得元素索引(这里假设如果有多个最大值,只返回第一个最大值索引),添加out参数:


static int Max(int[] intArray,out int maxIndex)
  {
   int maxVal = intArray[0];
   maxIndex = 0;
   for (int i = 1; i < intArray.Length; i++)
   {
    if(intArray[i]>maxVal)
    {
     maxVal = intArray[i];
     maxIndex = i;
    }
   }
   return maxVal;
  }

调用上面的代码:


 int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 };
 int maxIndex;
 Console.WriteLine("the maxium value is {0}", Max(myArray, out maxIndex));
 Console.WriteLine("the index of the maxium value is{0}", maxIndex + 1);

控制台输出的结果如下所示:

C#,out,参数,ref

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对ASPKU的支持。


注:相关教程知识阅读请移步到c#教程频道。