C# 6.0新特性(转载)

时间:2023-03-09 07:44:57
C# 6.0新特性(转载)

简介

VS 2015中已经包含C# 6.0. C#在发布不同版本时,C#总是会有新特性,比如C#3.0中出现LINQ,C#4.0中的动态特性,c#5.0中的异步操作等。.

C# 6.0中与增加了不少新的特性,帮助开发人员更好的编程。

下面的示例需要下载vs2015,这样才会有C#6.0环境,主要的新特性有:

  1. 使用Static参数,直接引用类中的方法或属性,不用每次都带上类名。
    using System; 
    using static System.Console; namespace CSharp6FeaturesDemo
    {
    class Program
    {
    static void Main(string[] args)
    {
    WriteLine("This is demo for C# 6.0 New Features");

    ReadLine();
    }
    }
    }
  2. 成员属性自动初始化,在定义属性时,即可通过简单的代码初始化属性的值,而不用在构造函数中初始化。
    public class Employee     
    {
    public Guid EmployeeId { get; set; } = Guid.NewGuid();
    public string FirstName { get; set; } = "Mukesh";
    public string LastName { get; set; } = "Kumar";
    public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } }
    }
  3. 集合中初始化成员的方式有所变化,变得更直观。
    Dictionary<int, string> myDictionary = new Dictionary<int, string>()             
    {
    [1] = "Mukesh Kumar",
    [2] = "Rahul Rathor",
    [3] = "Yaduveer Saini",
    [4] = "Banke Chamber"
    };
  4. 字符串格式化,以前要使用string.format("{0}-{1}",v1, v2); 来格式化输出,使用数字,容易出错,现在直接使用变量名
    Console.WriteLine($"The Full Name of Employee {firstName} {lastName}");
    
  5. C#6.0中,可以使用lambda表达式在一行内定义一个简单的函数,而不是传统的需要定义一个完整的函数。
    6.0之前
    public static string GetFullName(string firstName, string lastName)         
    {
    return string.Format("{0} {1}", firstName, lastName);
    }

    6.0中

    public static string GetFullName(string firstName, string lastName) => firstName + " " + lastName;

  6. C#6.0之前,一个属性需要同时定义get和set方法,即使set方法根本不需要,比如只读的属性。在C#6.0中,可以只定义一个get方法,并设置属性的初始值
    string FirstName { get; } = "Mukesh";
    
  7. 异常处理改进,以前异常处理中,需要在一个catch块中判断每个异常值的情况,然后执行不同的代码,而C#6.0中,可以定义多个 catch块,根据不同异常值处理不同的代码。
    try 
    {
    throw new Exception(errorCode.ToString());
    }
    catch (Exception ex) when (ex.Message.Equals("404"))
    { WriteLine("This is Http Error"); }
    catch (Exception ex) when (ex.Message.Equals("401"))
    { WriteLine("This is Unathorized Error"); }
    catch (Exception ex) when (ex.Message.Equals("403"))
    { WriteLine("Forbidden"); }
  8. Null值判断改进,以前操作某个变量需要判断是否null,否则程序抛出异常;在C#6.0中,可以使用一个简单的问号?即可自动判断是否null,如果是,则输出null值。
    //No need to check null in if condition             
    //null operator ? will check and return null if value is not there
    WriteLine(employees.FirstOrDefault()?.Name); //set the default value if value is null
    WriteLine(employees.FirstOrDefault()?.Name ?? "My Value");
  9. 变量声明改进,以前声明一个变量,用于从函数中返回值,需要在函数外定义,在C#6.0中,可直接在函数调用时定义变量。
    static void Main(string[] args)         
    {
    if (int.TryParse("20", out var result)) {
    return result;
    }
    return 0; // result is out of scope
    }

具体内容和示例代码可参考:

http://www.codeproject.com/Articles/1070659/All-About-Csharp-New-Features