第四章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
    }
}
相关推荐
摇滚侠32 分钟前
《SpringBoot 3:入门与应用实战》第 9 章 使用 WebMvc 开发应用 阅读笔记 1
spring boot·笔记·后端
用户83562907805135 分钟前
使用 Python 在 Excel 中插入 OLE 对象
后端·python
程序员小八7771 小时前
Go 语言特性
开发语言·后端·golang
XuCoder1 小时前
你以为隔离级别只是个开关,可 MySQL 凭什么靠它挡住幻读?
后端
创新技术阁1 小时前
FastapiAdmin 前后端启动全流程详解
前端·后端·fastapi
七牛开发者1 小时前
实测推荐 3 个 Skill,轻松上手 Codex 网页设计与交付流程
前端·javascript·后端
七牛开发者1 小时前
拆解 dsh 系列:从源码和版本变化看 DeepSeek Harness 的设计取舍
前端·javascript·后端
luteres1 小时前
Spring学习笔记
java·后端·spring
深念Y1 小时前
登录日志与管理员审计日志存储决策
前端·arm开发·后端·微服务·云原生·架构
用户8356290780512 小时前
使用 Python 为 PowerPoint 演示文稿添加评论
后端·python