C#中函数的使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo
{
    class Program
    {
        static int MaxValue(int[] intArray)
        {
            int maxVal = intArray[0];
            for (int i = 1;i<intArray.Length;i++)
            {
                if (intArray[i] > maxVal)
                {
                    maxVal = intArray[i];
                }
            }
            return maxVal;
        }

        static void Main(string[] args)
        {
            int[] myArray = { 1, 3, 5, 8, 2, 10, 9, 100, 40 };
            int maxVal = MaxValue(myArray);
            Console.WriteLine("最大值为:{0}",maxVal);
            Console.ReadKey();
        }
    }
}

params传参

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo
{
    class Program
    {
        static int MaxValue(params int[] intArray)
        {
            int maxVal = intArray[0];
            for (int i = 1;i<intArray.Length;i++)
            {
                if (intArray[i] > maxVal)
                {
                    maxVal = intArray[i];
                }
            }
            return maxVal;
        }

        static void Main(string[] args)
        {
            int maxVal = MaxValue(1,3,4,100,200,3);
            Console.WriteLine("最大值为:{0}",maxVal);
            Console.ReadKey();
        }
    }
}

out使用,类似于callback。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo
{
    class Program
    {
        static int MaxValue(out int maxIndex,params int[] intArray)
        {
            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;
        }

        static void Main(string[] args)
        {
            int maxIndex;
            int maxVal = MaxValue(out maxIndex,1,3,4,100,200,3);
            Console.WriteLine("最大值为:{0}",maxVal);
            Console.WriteLine("索引为:{0}", maxIndex);
            Console.ReadKey();
        }
    }
}

相关文章:

  • 2022-12-23
  • 2021-10-20
  • 2021-11-23
  • 2022-01-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-10
猜你喜欢
  • 2021-07-01
  • 2021-12-30
  • 2022-12-23
  • 2021-12-02
  • 2021-11-20
  • 2022-01-28
  • 2022-12-23
相关资源
相似解决方案