今天继续写上一篇文章C#4.0语法糖之第二篇,在开始今天的文章之前感谢各位园友的支持,通过昨天写的文章,今天有很多园友们也提出了文章中的一些不足,再次感谢这些关心我的园友,在以后些文章的过程中不断的完善以及自我提高,给各位园友们带来更好,更高效的文章。
废话就说到这里,下面正式进入我们的今天的C#4.0语法糖,今天给大家分享一下参数默认值、命名参数、对象初始化器和集合初始化器。
参数默认值和命名参数:方法的可选参数是.net 4.0最新提出的新的功能,对应简单的重载可以使用可选参数和命名参数混合的形式来定义方法这样就可以很高效的提供代码的运行效率。设计一个方法的参数的时,可为部分或全部参数分配默认值。调用其方法时,可以重新指定分配了默认值的参数,也可以使用默认值重新指定分配默认值的参数时,可以显式地为指定参数名称赋值,隐式指定的时候,是根据方法参数的顺序,靠c#编译器的推断。
我们用一个现实的例子来说明一下这个问题:比我我们有个这样的需求,有个客户类群体,他们的年龄默认都25岁,但是有些优质客户可以放宽年龄,可以是24岁或者26等等。下面我直接贴一下传统写法的代码:
1 public class Customer 2 3 { 4 5 //构造默认25岁年龄的客户 6 7 public Customer(string CustomerId, string CustomerName) 8 9 {10 11 this.Age = 25;12 13 this.CustomerId = CustomerId;14 15 this.CustomerName = CustomerName;16 17 }18 19 //构造不默认年龄的客户20 21 public Customer(string CustomerId, string CustomerName,int Age)22 23 {24 25 this.Age = Age;26 27 this.CustomerId = CustomerId;28 29 this.CustomerName = CustomerName;30 31 }32 33 public string CustomerId { get; set; }34 35 public int Age { get; set; }36 37 public string CustomerName { get; set; }38 39 }View Code输出代码:
1 //默认年龄的客户 2 3 Customer customer=new Customer("01","张三"); 4 5 Console.WriteLine("Id:"+customer.CustomerId+"名称"+customer.CustomerName+"年龄"+customer.Age); 6 7 Console.ReadLine(); 8 9 //指定年龄的客户10 11 Customer customerEx = new Customer("01", "张三",26);12 13 Console.WriteLine("Id:" + customerEx.CustomerId + "名称" + customerEx.CustomerName + "年龄" + customerEx.Age);14 15 Console.ReadLine();View Code
输出效果:
PR2ryhXssssBB5xwwtjGCe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