第四章c#方法-参数数组和可选参数(16)

1.方法参数

在方法中,对于参数的数量无法确定的时候,就用参数数组

js 复制代码
class TestClass
{
    public void Test(int a)
    {
        Console.WriteLine(a);
    }

    public void Test(int a,int b)
    {
        Console.WriteLine(a);
        Console.WriteLine(b);
    }

    public void Test(int a, int b, int c)
    {
        Console.WriteLine(a);
        Console.WriteLine(b);
        Console.WriteLine(c);
    }
}

2.参数数组

  1. 只有一个参数数组,传入的值分别存入数组中,可以不限数量,这里数量为3
  2. 用foreach循环,把这3个数依次输出出来
  3. 并将这3个数相加再输出
js 复制代码
//只有参数数组的情况
class TestClass
{
    public void TestMethod1(params int[] a) 
    {
        int num = 0;
        foreach (var item in a) 
        {
            num += item;
            Console.WriteLine(item);//依次输出1,2,3
        }
        Console.WriteLine(num);//6
    }
}

internal class Program
{
    static void Main(string[] args)
    {
        TestClass testclass = new TestClass();
        testclass.TestMethod1(1,2,3);
    }
}
  1. 既一个参数数组,又有参数的时候,a1为第一个传入的值,后面的值依次传入参数数组中
  2. 用foreach循环,把这后面2个数依次输出出来
  3. 并将这2个数相加再输出
js 复制代码
//既有参数数组的情况,又有参数的情况
class TestClass
{
    public void TestMethod2(int a1,params int[] a) 
    {
        int num = 0;
        foreach (var item in a) 
        {
            num += item;
            Console.WriteLine(item);//依次输出2,3
        }
        Console.WriteLine(num);//5
    }
}

internal class Program
{
    static void Main(string[] args)
    {
        TestClass testclass = new TestClass();
        testclass.TestMethod2(1,2,3);
    }
}

3.可选参数

  1. 遇到一个参数,我可能会调,可能不会调用,不知道什么时候调用的情况下使用
  2. 只调用参数的时候,那么就只修改参数的值,可选参数的值不会改变
  3. 又调用参数,也调用可选参数的时候,不仅修改参数的值,而且还修改可选参数的值
js 复制代码
class TestClass
{
    public void SelectParm(int a, int b = 100) 
    {
        Console.WriteLine($"{a} {b}");
    }
}

internal class Program
{
    static void Main(string[] args)
    {
        TestClass testclass = new TestClass();
        testclass.SelectParm(1);//1 100
        testclass.SelectParm(1,2);//1 2
    }
}
相关推荐
他们叫我秃子1 分钟前
前端开发转 Go 全栈(四):代码写在前面,却要最后执行?我终于搞懂了 defer
前端·后端·go
Csvn1 小时前
📊 SQL 入门 Day 14:聚合窗口函数 — 让 SUM / AVG 也能"滑动"起来
后端·sql
Oneslide1 小时前
K8s NodePort 端口为什么 netstat 查不到?
后端
北冥you鱼1 小时前
Go语言大数(big.Int)比较大小:原理、方法与最佳实践
开发语言·后端·golang
kkkAloha1 小时前
非对称加解密理解
后端
xcLeigh1 小时前
Go入门:零值与变量默认初始化机制
开发语言·后端·golang
鱼听禅2 小时前
C#学习笔记-添加编译参数到程序集自动更新程序编译时间
笔记·学习·c#
HySpark2 小时前
语音输入法实践:Rust 集成 Paraformer 推理引擎踩坑与优化过程
人工智能·后端·语音识别·熙瑾会悟
郡杰2 小时前
yudao-cloud及测试
后端
卷无止境2 小时前
Python 装饰器:给函数穿件"外套",到底难在哪?
后端·python