http://www.developer.com/net/csharp/top-10-c-6.0-language-features.html
1,单行函数表达式化
用=>简化只有一行的函数。
class Employee{ // Method with only the expression public static int CalculateMonthlyPay(int dailyWage) => dailyWage * 30;}
2,?--条件 运算符
以前需要显式地写判断非空的条件语句
private void GetMiddleName(Employee employee){ string employeeMiddleName = "N/A"; if (employee != null && employee.EmployeeProfile != null) employeeMiddleName = employee.EmployeeProfile.MiddleName;}
现在可以用一行代码搞定
private void GetMiddleName(Employee employee){ string employeeMiddleName = employee?.EmployeeProfile?.MiddleName ?? "N/A";}
3,自动属性初始化器
不用再弄一个private的set和类变量了。如下:
class PeopleManager{ public List<string> Roles { get; } = new List<string>() { "Employee", "Managerial"};}
通过在类的定义这一层级声明构造函数的入参,取代一个单独的构造函数。入参的范围是类范围,且只在类的初始化时有效,与自动属性初始化器搭配起来好干活。
// Primary constructorclass Basket(string item, int price){ // Using primary constructor parameter values // to do auto property initialization. public string Item { get; } = item; public int Price { get; } = price;}
5,在函数调用时声明OUT参数
避免在调用函数之前还得专门定义一个out类型的参数:
public bool ConvertToIntegerAndCheckForGreaterThan10(string value){ if (int.TryParse(value, out int convertedValue) && convertedValue > 10) { return true; } return false;}
6,在Catch语句中用await
这样就可以在一个异步操作中处理异步过程中的异常了。
public async void Process(){ try { Processor processor = new Processor(); await processor.ProccessAsync(); } catch (Exception exception) { ExceptionLogger logger = new ExceptionLogger(); // Catch operation also can be aync now!! await logger.HandleExceptionAsync(exception); }}
可以选择不处理某些异常类型了。
public async void Process(){ try { DataProcessor processor = ne } // Catches and handles only non sql exceptions catch (Exception exception) if(exception.GetType() != typeof(SqlException)) { ExceptionLogger logger = new ExceptionLogger(); logger.HandleException(exception); }}
以减少重复代码,比如using Console这个静态类:
using System;// A static class inclusionusing System.Console;namespace CSharp6Demo{ class Program { static void Main(string[] args) { WriteLine("Console. is not required as it is included in the usings!"); } }}
9,字符串插入值
可以认为是String.Format的改进,可以不再用替代符了,而是直接用变量。
static void Main(string[] args){ string name = "Robert"; string car = "Audi"; WriteLine("\{name}'s favourite car is {car}!");}
10,Roslyn,新的编译器
开源,且有一个接口供扩展。可以认为是“像服务一样的编译器”。