阅读:8534回复:1
C# 可选参数的定义及使用C# 如果使用可选参数,这对于程序的开发就大大的提供了方便,而不用造成多种方法的超多参数重载 以来内容为转载,部分经过修改。 ============================================== 1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Show(); 6 Show("TonyKent"); 7 Console.ReadLine(); 8 } 9 10 public static void Show(string msg = "") 11 { 12 Console.WriteLine("Hello {0}",msg); 13 } 14 } ![]() 参数默认值, 有了这个, 好多方法的重载可以减少了~ 2010-09-06 补充: 在使用命名参数时, 如果使用多个可选参数, 必须都放在参数列表的最后. 而且在调用方法时, 可以选择对可选参数进行赋值, 如下: ![]() ![]() 2 { 3 static void Main(string[] args) 4 { 5 Show("2010-09-06"); 6 Show("2010-09-06", "World", "Morning"); 7 Show("2010-09-06", msg: "Morning"); 8 Console.ReadLine(); 9 } 10 11 public static void Show(string date, string name = "TonyKent", string msg = "") 12 { 13 Console.WriteLine("{0} Hello {1} {2}!", date, name, msg); 14 } 15 } ![]() 上面代码执行结果如下: 2010-09-06 Hello TonyKent! 2010-09-06 Hello World Morning! 2010-09-06 Hello TonyKent Morning! 可见, 可选参数选择使用时, 用参数名+":"去直接命名强制使用. |
|
最新喜欢:![]()
|