C#可选参数用法示例介绍

2021年5月8日16:25:10 发表评论 1,157 次浏览

顾名思义, 可选参数不是强制性参数, 它们是可选参数。它有助于排除某些参数的参数。或者我们可以说在可选参数中, 没有必要在方法中传递所有参数。这个概念在C#4.0.

重要事项:

  • 你可以在以下位置使用可选参数方法, 建设者, 索引器和代表们.
  • 每个可选参数都包含一个默认值, 这是其定义的一部分。
  • 如果我们没有将任何参数传递给可选参数, 那么它将采用其默认值。
  • 可选参数的默认值是一个常量表达式。
  • 可选参数始终在参数列表的末尾定义。换句话说, 方法, 构造函数等的最后一个参数是可选参数。

例子:

静态公共无效学者(字符串fname, 字符串lname, int年龄= 20, 字符串分支="计算机科学")

在上面的示例中, 年龄= 20和字符串分支="计算机科学"是可选参数, 具有其默认值。让我们借助示例来讨论可选参数的概念。

//C# program to illustrate the
//concept of optional parameters
using System;
  
class GFG {
  
     //This method contains two regular
     //parameters, i.e. fname and lname
     //And two optional parameters, i.e.
     //age and branch
     static public void scholar( string fname, string lname, int age = 20, string branch = "Computer science" )
  
     {
         Console.WriteLine( "First name: {0}" , fname);
         Console.WriteLine( "Last name: {0}" , lname);
         Console.WriteLine( "Age: {0}" , age);
         Console.WriteLine( "Branch: {0}" , branch);
     }
  
     //Main Method
     static public void Main()
     {
  
         //Calling the scholar method
         scholar( "Ankita" , "Saini" );
         scholar( "Siya" , "Joshi" , 30);
         scholar( "Rohan" , "Joshi" , 37, "Information Technology" );
     }
}

输出如下:

First name: Ankita
Last name: Saini
Age: 20
Branch: Computer science
First name: Siya
Last name: Joshi
Age: 30
Branch: Computer science
First name: Rohan
Last name: Joshi
Age: 37
Branch: Information Technology

说明:在以上示例中, 学者方法包含这四个参数中的四个参数, 两个是常规参数, 即名和名字两个是可选参数, 即年龄和科。这些可选参数包含其默认值。当你不传递这些参数的值时, 可选参数将使用其默认值。当你为可选参数传递参数时, 它们将采用传递的值而不是其默认值。

如果我们使用除最后一个参数以外的可选参数会发生什么?

它将给出编译时错误"可选参数不能在必需参数之前"作为可选参数, 总是在参数列表的末尾定义。换句话说, 方法, 构造函数等的最后一个参数是可选参数。

例子:

//C# program to illustrate the concept
//of optional parameters
using System;
  
class GFG {
  
     //This method contains two regular
     //parameters, i.e. fname and lname
     //And one optional parameters, i.e. age
     static public void scholar( string fname, int age = 20, string lname)
     {
         Console.WriteLine( "First name: {0}" , fname);
         Console.WriteLine( "Last name: {0}" , lname);
         Console.WriteLine( "Age: {0}" , age);
     }
  
     //Main Method
     static public void Main()
     {
  
         //Calling the scholar method
         scholar( "Ankita" , "Saini" );
     }
}

编译时错误:

prog.cs(11, 26):错误CS1737:可选参数不能在必需参数之前


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: