C# params 可变参数

1、声明

修饰词  返回值 函数名(params int[] 参数名)

2、调用

a、函数名(参数1,参数2,...)

b、函数名(new int[]{参数1, 参数2})

3、注意

a、可变参数要放在最后

b、params关键字后面加数组

c、可以配合ref和out使用,ref out 后面加数据类型

4、案例

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

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int result = 0;
            Add(ref result, 1, 3, 5, 7);
            Console.WriteLine(result);
            int res;
            Add2(out res, 2, 4, 9);
            Console.WriteLine(res);
        }

        public static void Add(ref int result, params int[] sums) 
        {
            for (int i = 0; i < sums.Length; i++)
            {
                result += sums[i];
            }
        }

        public static void Add2(out int result, params int[] sums)
        {
            result = 0;
            for (int i = 0; i < sums.Length; i++)
            {
                result += sums[i];
            }
        }
    }
}

 

posted @ 2025-06-18 20:57  市丸银  阅读(17)  评论(0)    收藏  举报