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);
}

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值