C#基础-out,ref,params

2021/9/11 11:05:17

本文主要是介绍C#基础-out,ref,params,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

out

再说out参数之前先做个练习题
Q1:写一个方法 求一个数组中的最大值,最小值,总和,平均值?
(先用传统方法返回一个数组来装这四个值 然后再使用out参数做对比)

static void Main(string[] args)
{
      int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
      int[] res =  GetMaxMinSumAvg(nums);
      Console.WriteLine("最大值{0},最小值{1},总和{2},平均值{3}", res[0], res[1], res[2], res[3]);
      Console.ReadKey();
  }
  
public static int[] GetMaxMinSumAvg(int[] nums)
{
    int[] res = new int[4];
    res[0] = nums[0];//假设最大值 依次给数组赋值
    res[1] = nums[0];//假设最小值
    res[2] = nums[0];//假设总和
    for (int i = 0; i < nums.Length; i++)
    {
        if (nums[i] > res[0])
        {
            res[0] = nums[i];
        }
        if (nums[i] < res[1])
        {
            res[1] = nums[i];
        }
        res[2] += nums[i];
       
    }
    res[3] = res[2] / res.Length;
    return res;
}

但这种只能返回同一个类型多个数组的值,如果想返回多个不同类型的多个值时 此时数组是不成立的
因此我们这时就使用out参数,可以多余返回不同类型的参数

static void Main(string[] args)  
{
     //写一个方法,求一个数组中的最大值,最小值,总合,平均值
     int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
     int max;
     int min;
     int sum;
     int avg;
     GetMaxMinSumAvg(nums,out max,out min,out sum,out avg);
     Console.WriteLine("最大值{0},最小值{1},总和{2},平均值{3}",max, min,sum,avg);
     Console.ReadKey();
 }

public static void GetMaxMinSumAvg(int[] nums,out int max,out int min,out int sum,out int avg)
{
    max = nums[0];
    min = nums[0];
    sum = 0;
    avg = 0;
    for (int i = 0; i < nums.Length; i++)
    {
        if (nums[i]>max)
        {
            max = nums[i];
        }
        if (nums[i]<min)
        {
            min = nums[i];
        }
        sum += nums[i];
    }
    avg = sum / nums.Length;
}

结果都是
在这里插入图片描述


ref

ref就是将这两个值在方法内进行改变,改变后再将值带出去
Q1:用一个方法来交换方法内的两个变量的值?

 static void Main(string[] args)  
 {
     //用一个方法来交换方法内的两个变量的值
     int n1 = 10;
     int n2 = 20;
     Test(ref n1,ref n2);//ref就是将这两个值在方法内进行改变,改变后再将值带出去 ,然而必须在方法内进行赋值,因为你要有值可以改变
     Console.WriteLine("n1的值{0},n2的值{1}",n1,n2);
     Console.ReadKey();
 }

 public static void Test(ref int n1,ref int n2)
 {
      int temp = n1 ;
      n1 = n2;
      n2 = temp;
  }

结果是
在这里插入图片描述


params

params可变参数:将实参列表中跟可变参数数组类型一致的元素都当做数组的元素去处理
params可变参数必须是形参列表中的最后一个元素
Q1:用一个方法求张三的总成绩?

 static void Main(string[] args)  
 {
     //用一个方法求张三的总成绩
     Test("张三", 99, 88, 77);
     Console.ReadKey();
 }
public static void Test(string name, params int[] score)
{
    int sum = 0;
    for (int i = 0; i < score.Length; i++)
    {
        sum += score[i];
    }
    Console.WriteLine("{0}这次考试的总成绩是{1}", name, sum);
}

结果是
在这里插入图片描述



这篇关于C#基础-out,ref,params的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程