首页 > 编程语言 >《c#高级编程》第4章C#4.0中的更改(七)——命名参数和可选参数

《c#高级编程》第4章C#4.0中的更改(七)——命名参数和可选参数

时间:2023-04-25 09:03:18浏览次数:29  
标签:4.0 firstName c# lastName age 参数 PrintPerson string

一、概念
C#中的命名参数和可选参数是两种函数参数的特殊形式,它们可以提高代码的可读性和灵活性。

命名参数

命名参数允许我们在调用函数时指定参数名称,从而不必按照函数定义时的参数顺序进行传参。这样做可以使代码更加易读易懂,同时也可以提高代码的灵活性,因为我们可以只传递某些参数来设置默认值。

以下是一个使用命名参数的示例:

void PrintPerson(string firstName, string lastName, int age) {
Console.WriteLine($"Name: {firstName} {lastName}, Age: {age}");
}

// 使用命名参数调用PrintPerson函数
PrintPerson(lastName: "Smith", firstName: "John", age: 30);

在上面的示例中,我们使用了命名参数来调用PrintPerson函数,并且没有按照函数定义时的参数顺序进行传参。由于我们指定了每个参数的名称,因此代码更加易读易懂。

注意,当我们使用命名参数时,可以省略一些参数并采用默认值,但不能跳过非可选参数。例如,下面的代码是无法编译通过的:

PrintPerson(lastName: "Smith"); // 编译错误:缺少必需的参数 'firstName' 和 'age'

可选参数

可选参数允许我们在函数定义时为某些参数指定默认值,从而在调用函数时可以不传递这些参数。这样做可以提高代码的灵活性,因为我们可以只传递需要的参数,而不必传递所有参数。

以下是一个使用可选参数的示例:

void PrintPerson(string firstName, string lastName, int age = 18) {
Console.WriteLine($"Name: {firstName} {lastName}, Age: {age}");
}

// 调用PrintPerson函数
PrintPerson("John", "Smith"); // 输出结果:Name: John Smith, Age: 18
PrintPerson("Mary", "Johnson", 25); // 输出结果:Name: Mary Johnson, Age: 25

在上面的示例中,我们定义了一个可选参数age,并将其默认值设置为18。当我们调用PrintPerson函数时,如果没有传递age参数,则会使用默认值。

注意,当我们使用可选参数时,必须将它们放在函数签名的末尾,并且不能使用ref或out关键字。例如,下面的代码是无法编译通过的:

void PrintPerson(string firstName, string lastName, ref int age = 18) { // 编译错误:可选参数不能使用ref或out关键字
Console.WriteLine($"Name: {firstName} {lastName}, Age: {age}");
}

总之,命名参数和可选参数都是C#中非常有用的语言特性,它们能够提高代码的可读性和灵活性,使程序变得更加易于维护和扩展。

二、实例

命名参数和可选参数的应用场景非常广泛,以下是一些经典的应用场景,并附有相应的代码示例:

命名参数

  1. 函数具有多个参数,但我们只关心其中的某几个参数。
void PrintPerson(string firstName, string lastName, int age) {
    Console.WriteLine($"Name: {firstName} {lastName}, Age: {age}");
}

// 使用命名参数调用PrintPerson函数,只传递了需要的参数
PrintPerson(lastName: "Smith", firstName: "John");
  1. 函数中具有相同类型的多个参数,使用命名参数可以提高代码的可读性。
void Search(int id, string name, string address) {
    // ...
}

// 使用命名参数调用函数Search,可以清楚地表明每个参数的含义
Search(id: 1, name: "John", address: "123 Main St.");

可选参数

  1. 函数中某些参数的默认值可能经常被使用。例如,在创建一个窗口时,我们可以将宽度和高度设置为可选参数,并将其默认值设置为800和600,因为这是大多数用户所期望的窗口大小。
void CreateWindow(int width = 800, int height = 600) {
    // ...
}

// 调用CreateWindow函数,不传递可选参数
CreateWindow(); // 窗口大小为800x600

// 调用CreateWindow函数,只传递一个可选参数
CreateWindow(width: 1024); // 窗口大小为1024x600

// 调用CreateWindow函数,传递两个可选参数
CreateWindow(width: 1024, height: 768); // 窗口大小为1024x768
  1. 函数中的某些参数是可选的,但如果提供了,则必须按照特定的格式进行传递。例如,在打印日志时,我们可以将时间戳设置为一个可选参数,并将其默认值设置为当前时间。
void Log(string message, DateTime timestamp = default(DateTime)) {
    if (timestamp == default(DateTime)) {
        timestamp = DateTime.Now;
    }
    Console.WriteLine($"[{timestamp}] {message}");
}

// 调用Log函数,不传递可选参数
Log("Hello World!"); // 输出结果:[2021/10/01 12:00:00] Hello World!

// 调用Log函数,传递时间戳作为可选参数
Log("Hello World!", new DateTime(2021, 9, 30, 23, 59, 59)); // 输出结果:[2021/09/30 23:59:59] Hello World!

总之,命名参数和可选参数是一种非常有用的C#语言特性,它们能够提高代码的可读性和灵活性。在实际开发中,我们应该根据具体场景选择合适的参数传递方式,以使代码更加清晰易懂。

标签:4.0,firstName,c#,lastName,age,参数,PrintPerson,string
From: https://www.cnblogs.com/DinAction/p/17351541.html

相关文章

  • windows+centos+ubuntu多系统环境,ubuntu启动修复
    故障现象:       在windows中调整分区后,ubuntu系统无法启动,centos启动进入保护模式解决过程一、双硬盘,centos硬盘EFI分区还在,ubuntu硬盘EFI分区消失,发现一个300的分区但是不是efi分区,查看分区无数据重建EFI分区fdisk/dev/nvme0n1p1  d删除原有分区n新建分区 ......
  • K8s 集群 etcd节点故障解决方案
    1环境说明k8s版本:v1.20etcd节点(192.168.0.12)故障: 报错详情: 4月2422:47:13k8s-node2etcd[9543]:{"level":"warn","ts":"2023-04-24T22:47:13.571+0800","caller":"etcdserver/server.go:2065","msg":......
  • 解决npm install各种报错的6种方案 Error: Command failed: cmd.exe autoreconf -ivf
    报错示例:Error:Commandfailed:C:\Windows\system32\cmd.exe/s/c"autoreconf-ivf"gifsiclepre-buildtestfailedPSG:\code_all\my_webpack_webgl2021-5-17-dev_01\three151-demo>npminstallnpmnoticeBeginningOctober4,2021,allconnect......
  • CodeStar2023年春第6周周赛普及进阶组
    T1:最长倍数序列本题难度中等,先把\(a\)从小到大排序。dp[i]表示以\(a_i\)结尾的倍数序列。转移如下:只有\(a_i\),对应长度\(dp[i]=1\)上一个数是\(a_j(1\leqslantj\leqslanti-1)\),若\(a_j\)是\(a_i\)的约数,就更新\(dp[i]=\max(dp[i],dp[j]+1)\)最终答......
  • 自定义Python版本ESL库访问FreeSWITCH
    环境:CentOS7.6_x64Python版本:3.9.12FreeSWITCH版本:1.10.9一、背景描述ESL库是FreeSWITCH对外提供的接口,使用起来很方便,但该库是基于C语言实现的,Python使用该库的话需要使用源码进行编译。如果使用系统自带的Python版本进行编译,过程会比较流畅,就不描述了。这里记录下使用自定义......
  • Reset an Internet Connection (Flush DNS)
    https://support.pearson.com/getsupport/s/article/Reset-an-Internet-Connection-Flush-DNSWindows10.8and8.1Navigatetothedesktop.(FromHome,taporclicktheDesktoptile).Right-clicktheStartbutton(theWindowslogointhelower-left).ChooseComma......
  • Codeforces Round #459 (Div. 2) D. MADMAX DAG&&博弈
    Asweallknow,Maxisthebestvideogameplayeramongherfriends.Herfriendsweresojealousofhers,thattheycreatedanactualgamejusttoprovethatshe’snotthebestatgames.Thegameisplayedonadirectedacyclicgraph(aDAG)withnvertic......
  • 2016 ACM/ICPC Asia Regional Qingdao Online E
    Rock-paper-scissorsisazero-sumhandgameusuallyplayedbetweentwopeople,inwhicheachplayersimultaneouslyformsoneofthreeshapeswithanoutstretchedhand.Theseshapesare“rock”,“paper”,and“scissors”.Thegamehasonlythreepossible......
  • 2017 ACM-ICPC, Universidad Nacional de Colombia Programming Contest D
    AlexhastwomagicmachinesAandB.MachineAwillgiveyou2x + 1coinsifyouinsertxcoinsinit,machineBwillgiveyou2x + 2.Alexhasnocoinsandwantstogetexactlyncoinsinordertobuyanewunicorn,buthecan’tfigureouthowtodoi......
  • 2016 ACM/ICPC Asia Regional Qingdao Online B
    Givenanintegern,weonlywanttoknowthesumof1/k2wherekfrom1ton.InputTherearemultiplecases.Foreachtestcase,thereisasingleline,containingasinglepositiveintegern.Theinputfileisatmost1M.OutputTherequiredsum,......