C#进阶可选参数和命名参数

1简单实现:

public static class Program { 
       
private static Int32 s_n = 0
       
public static void M(Int32 x = 11, String s = "1A", DateTime dt = default(DateTime), Guid guid = new Guid()) { 
           Console.WriteLine(
"x={0}, s={1}, dt={2}, guid={3}", x, s, dt, guid); 
       } 
       
public static void Main() { 
           
// 1. Same as: M(9, "A", default(DateTime), new Guid()); 
           M(); 
           
// 2. Same as: M(8, "X", default(DateTime), new Guid()); 
           M(8"X"); 
           
// 3. Same as: M(5, "A", DateTime.Now, Guid.NewGuid()); 
           M(5, guid: Guid.NewGuid(), dt: DateTime.Now); 
           
// 4. Same as: M(0, "1", default(DateTime), new Guid()); 
           M(s_n++, s_n++.ToString()); 
           
// 5. Same as: String t1 = "2"; Int32 t2 = 3; 
           
// M(t2, t1, default(DateTime), new Guid()); 
           M(s: (s_n++).ToString(), x: s_n++); 
           Console.ReadLine(); 
       } 
   }

2但是如果指定参数的一个实现非常容易造成版本兼容的问题

可选参数,属于一种有争议的东西。
使用可选择参的确很方便,但是,一旦跨编译器,或跨语言的时候,甚至,在继随时就有麻烦了。
默认参数的默认值应该是多少,这需要从原来的程序中获得。而一旦原来的程序版本升级时改了默认值,那就完蛋了。
在继承时,如果继承的函数默认值被改了,也是一个很令人头晕的事。

来自这里

但是我们可以有以下相对好的解决方案,问题并没有彻底解决,事物往往有两面性。

默认实现一般都null /0 给出对比:

1 //不好的写法
2 private static String MakePath(String filename = "Untitled") { 
3 return String.Format(@"C:\{0}.txt", filename); 
4 
5 // 较好的写法 
6 private static String MakePath(String filename = null) { 
7 return String.Format(@"C:\{0}.txt", filename ?? "Untitled"); 
8 }

3扩展阅读

C#团队还利用C# 4作为晚绑定的途径来支持DLR(dynamic language runtime)。事实上,这才是可选参数真正的目的,其他都是附带的便利。由于动态语言没有显式的类型声明,无法基于参数类型进行函数重载,因此可选参数是非常必要的。---infoq

http://kb.cnblogs.com/page/67822/

原文地址:https://www.cnblogs.com/facingwaller/p/1917062.html