C#6.0新特性

來源:互聯網
上載者:User

標籤:

一、C#發展曆程

是自己整理列出了C#每次重要更新的時間及增加的新特性,對於瞭解C#這些年的發展曆程,對C#的認識更加全面,是有協助的。

二、C#6.0新特性

1、字串插值 (String Interpolation)

字串拼接最佳化

Before:

var Name = "joye.net";var Results = "Hello" + Name;//直接拼接var results1 = string.Format("Hello {0}", Name);//Format拼接

After:

var results2 = $"Hello {Name}"; //$拼接var results= $"Hello {Name}{new Program().GetCnblogsSite()}";//{}可以直接插入代碼

2、null檢查運算子【 ?.】 (Monadic null checking)

null最佳化

Before:

        public static string GetCnblogsSite()        {            return "http://www.cnblogs.com/yinrq";        } 
Program pro = null;if(pro!=null)      Console.WriteLine(GetCnblogsSite());

After:

Program pro = null;Console.WriteLine(pro?.GetCnblogsSite());

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

可以直接給自動屬性賦值了,不需要寫在建構函式中。

Before:

    public class ClassA    {        private string Name{get;set;};        public ClassA()        {            Name = "joye.net";        }     }

After:

    public class ClassA    {        public string Name { get; set; } ="joye.net";       }

 4、唯讀自動屬性(Getter-only auto-properties)

唯讀自動屬性可以直接初始化,或者在建構函式中初始化。

before

 //縮小自動屬性的存取權限    public class ClassA    {        public string Name { get; private set; }       }    //C#1.0實現    public class ClassA    {        private string Name = "joye.net";        public string Name        {            get { return Name; }        }    }

after:

    public class ClassA    {        public string Name { get; } = "joye.net";    }

5、運算式方法體(Property Expressions && Method Expressions)

唯讀屬性,唯讀索引器和方法都可以使用Lambda運算式作為Body。

一句話的方法體可以直接寫成箭頭函數,而不再需要大括弧(分頁控制項http://www.cnblogs.com/yinrq/p/5586841.html就用到了屬性運算式Property Expressions)

    public class PagerInBase    {        /// <summary>        /// 當前頁        /// </summary>        public int PageIndex { get; set; }        /// <summary>        /// 頁數        /// </summary>        public int PageSize { get; set; }     
//以前的寫法
     //public int Skip{get{return (PageIndex - 1) * PageSize}}
//跳過序列中指定數量的元素 public int Skip => (PageIndex - 1) * PageSize; /// <summary> /// 請求URL /// </summary> public string RequetUrl => System.Web.HttpContext.Current.Request.Url.OriginalString; /// <summary> /// 建構函式給當前頁和頁數初始化 /// </summary> public PagerInBase() { if (PageIndex == 0) PageIndex = 1; if (PageSize == 0) PageSize = 10; } }

方法運算式(Method Expressions)

        //before 的完整方法        public int Skip()        {             return (PageIndex - 1) * PageSize        }        //After C#6.0 方法運算式        public int Skip() => (PageIndex - 1) * PageSize;

6、using靜態類(Static type using statements)

using System;using static System.Math;namespace ConsoleApplication1    {        class Program        {            static void Main(string[] args)            {                Console.WriteLine(Log10(5) + PI);            }        }    }

 7、檢查方法參數nameof運算式(nameof expressions)

這個很有用,原來寫WPF中的ViewModel層的屬性變化通知時,需要寫字串,或者使用MvvmLight等庫中的協助方法,可以直接傳入屬性,但由於是在運行時解析,會有少許效能損失。現在使用nameof運算子,保證重構安全和可讀性,又提升了效能。

Before:

        public static void Add(Person person)        {            if (person == null)            {                throw new ArgumentNullException("person");            }        }

After:

        public static void Add(Person person)        {            if (person == null)            {                throw new ArgumentNullException(nameof("person"));            }        }

8、帶索引的對象初始化器(Index initializers )

直接通過索引進行對象的初始化

var dic = new Dictionary<int, string> { [0]="joye.net",[1]= "http://yinrq.cnblogs.com/",[2]= "Index initializers " };

9、catch和finally 中使用await (catch和finally 中的 await )

在C#5.0中,await關鍵字是不能出現在catch和finnaly塊中的。而C#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(); // finally and do this.             }

10、內聯out參數(Inline declarations for out params)

before

int x;int.TryParse("123", out x);

after:

int.TryParse("123", out int x);

11、無參數的結構體建構函式(Parameterless constructors in structs)

    public struct MyStruct    {        public int A { get; }        public int B { get; }        public MyStruct(int a, int b) { A = a; B = b; }        public MyStruct(): this(0, 1) { }    }
     WriteLine(new MyStruct().ToString());     WriteLine(default(MyStruct).ToString());
三、代碼
using System;using System.Collections.Generic;using static System.Console;namespace ConsoleApplication1{    public class MyClass    {        public int A { get; set; }        public int B { get; set; } = 1;        public string Separator { get; } = "/";        public string SeparatorSpaces { get; } = string.Empty;        public double Value => (double)A / B;        public int this[int index] => index == 0 ? A : B;        public int this[string index] => index == "A" ? A : B;        public override string ToString() => "{A}{SeparatorSpaces}{Separator}{SeparatorSpaces}{B}";        public void Print() => WriteLine(ToString());        public MyClass()        {        }        public MyClass(int a, int b)        {            A = a;            B = b;        }        public MyClass(int a, int b, string separatorSpaces) : this(a, b)        {            SeparatorSpaces = separatorSpaces;            if (string.IsNullOrEmpty(separatorSpaces))            {                throw new ArgumentNullException(nameof(separatorSpaces));            }        }        public static readonly Dictionary<string, MyClass> Dic =            new Dictionary<string, MyClass>            {                ["zero"] = new MyClass(),                ["one"] = new MyClass(1, 1),                ["half"] = new MyClass(1, 2),                ["quarter"] = new MyClass(1, 4),                ["infinity"] = new MyClass(1, 0),            };    }    public struct MyStruct    {        public int A { get; }        public int B { get; }        public MyStruct(int a, int b) { A = a; B = b; }        public MyStruct(): this(0, 1) { }        public override string ToString() => "{A}{B}";    }    class Program    {        static void Main(string[] args)        {            foreach (var f in MyClass.Dic)            {                WriteLine("{f.Key} : {f.Value.Value}");            }            var fraction = new MyClass(1, 3, " ");            fraction.Print();            try            {                fraction = new MyClass(1, 2, null);            }            catch (ArgumentNullException e)            {                if (e.ParamName == "separatorSpaces")                    WriteLine("separatorSpaces can not be null");            }            MyClass v;            MyClass.Dic.TryGetValue("harf", out v);            v?.Print();            var a = v?.A;            WriteLine(a == null);            var b = v?["B"];            WriteLine(b == null);            WriteLine(v?.ToString() == null);            WriteLine(new MyStruct().ToString());            WriteLine(default(MyStruct).ToString());        }    }}

C#6.0新特性

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.