C#6.0 中的那些新特性


C#6.0 中的那些新特性

前言  

      VS2015在自己機器上確實是裝好了,費了老勁了,想來體驗一下跨平台的快感,結果被微軟狠狠的來了一棒子了,裝好了還是沒什么用,應該還需要裝Xarmain插件,配置一些參數吧,由於這塊之前從未接觸過,想了想還是先不把時間繼續浪費在這里了,於是乎來體驗一下新特性了。

  本人個人博客原文鏈接地址為http://aehyok.com/Blog/Detail/66.html

    本文參考http://roslyn.codeplex.com,參考PDF文檔http://files.cnblogs.com/aehyok/VS2015CSharp6.0.pdf

1、自動屬性的增強

1.1、自動屬性初始化 (Initializers for auto-properties)

C#4.0下的果斷實現不了的。

C#6.0中自動屬性的初始化方式

只要接觸過C#的肯定都會喜歡這種方式。真是簡潔方便呀。

 

 1.2、只讀屬性初始化Getter-only auto-properties

先來看一下我們之前使用的方式吧

復制代碼
    public class Customer
    {
        public string Name { get; }

        public Customer(string firstName,string lastName)
        {
            Name = firstName +" "+ lastName;
        }
    }
復制代碼

再來看一下C#6.0中

    public class Customer
    {
        public string FirstName { get; }="aehyok";
        public string LastName { get; }="Kris";

    }

和第一條自動屬性初始化使用方式一致。

2、Expression bodied function members

2.1 用Lambda作為函數體Expression bodies on method-like members

public Point Move(int dx, int dy) => new Point(x + dx, y + dy);  

再來舉一個簡單的例子:一個沒有返回值的函數

public void Print() => Console.WriteLine(FirstName + " " + LastName);

 

2.2、Lambda表達式用作屬性Expression bodies on property-like function members

        public override string ToString()
        {
            return FirstName + " " + LastName;
        }

現在C#6中

復制代碼
    public class User
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public override string ToString() => string.Format("{0}——{1}", FirstName, LastName);

        public string FullName => FirstName + " " + LastName;
    }
復制代碼

 

3、引用靜態類Using Static 

 在Using中可以指定一個靜態類,然后可以在隨后的代碼中直接使用靜態的成員

 

4、空值判斷Null-conditional operators  

 直接來看代碼和運行結果

 通過結果可以發現返回的都為null,再也不像以前那樣繁瑣的判斷null勒。

 

5、字符串嵌入值    

在字符串中嵌入值

之前一直使用的方式是

現在我們可以簡單的通過如下的方式進行拼接

6、nameof表達式nameof expressions 

 在方法參數檢查時,你可能經常看到這樣的代碼(之前用的少,這次也算學到了)

復制代碼
        public static void AddCustomer(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }
        }
復制代碼

里面有那個customer是我們手寫的字符串,在給customer改名時,很容易把下面的那個字符串忘掉,C#6.0 nameof幫我們解決了這個問題,看看新寫法

復制代碼
        public static void AddCustomer(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }
        }
復制代碼

 

7、帶索引的對象初始化器Index initializers   

 直接通過索引進行對象的初始化,原來真的可以實現

通過這種方式可以發現字典中只有三個元素,所以也就只有這三個索引可以訪問額,其他類型的對象和集合也是可以通過這種方式進行初始化的,在此就不進行一一列舉了。

8、異常過濾器 (Exception filters)  

先來看一個移植過來的方法

復制代碼
            try
            {
                var numbers = new Dictionary<int, string> {[7] = "seven",[9] = "nine",[13] = "thirteen" };
            }
            catch (ArgumentNullException e)
            {
                if (e.ParamName == "customer")
                {
                    Console.WriteLine("customer can not be null");
                }
            }
復制代碼

在微軟的文檔中還給出了另一種用法,這個異常會在日志記錄失敗時拋給上一層調用者

復制代碼
        private static bool Log(Exception e)
        {
            ///處理一些日志
            return false;
        } 

        static void Main(string[] args)
        {

            try
            {
                ///
            }
            catch (Exception e){if (!Log(e))
                {

                }
            }

            Console.ReadLine();
        }
復制代碼

 

9、catch和finally 中的 await —— Await in catch and finally blocks

 在C#5.0中,await關鍵字是不能出現在catch和finnaly塊中的。而在6.0中

復制代碼
            try
            {
                res = await Resource.OpenAsync(…); // You could do this. … 
            }
            catch (ResourceException e)
            {
                await Resource.LogAsync(res, e); // Now you can do this … 
            } finally
            {
                if (res != null)
                    await res.CloseAsync(); // … and this. 
            } 
復制代碼

 

10、無參數的結構體構造函數—— Parameterless constructors in structs 

 

總結  

之前看到有大神發過一篇文章http://www.cnblogs.com/henryzhu/p/new-feature-in-csharp-6.html,自己還是禁不住想來切身的體驗一番。感覺很不錯。 也學到了不少新東西。

 
分類:  C#
標簽:  VS2015


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM