- 靜態(tài)using(static using)。引用靜態(tài)類后,可以直接方法名
old: using System; Console.WriteLine("Hello, World!"); new: using static System.Console; WriteLine("Hello, World");
- 表達式方法?使用表達式方法,只有一條語句的方法可以使用lambda語法寫。
old: bool IsSquare(Vector2 v2) { return v2.x == v2.y; } new: bool IsSquare(Vector2 v2) => v2.x == v2.y;
- 表達式屬性
old: public string FullName get { return FirstName +"" + LastName; } new: public string FullName => FirstName +"" + LastName;
- 自動屬性初始化
old: public int Age { get; set; } new: public int Age { get; set; } = 34;
- 只讀自動屬性
old: private readonly int _bookId; public BookId { get { return _bookId; } } new: public BookId {get;}
- nameof操作符?字段、屬性、方法和類型的name可以通過nameof訪問。使用nameof,可以方便的重構name變化
old: public void Method(object o) { if (o == null) throw new ArgumentNullException("o"); } new: public void Method(object o) { if (o == null) throw new ArgumentNullException(nameof(o)); }
- Null傳遞操作符(?.)
handler?.Invoke(source, e);
- 字符串插值($)
$"name={Name},age={Age}"
- 字典初始化器
old" var dict = new Dictionary<int, string>() { {3, "three"}, {7, "seven"} } new: var dict = new Dictionary<int, string>() { [3] = "three", [7] = "seven" }
- 異常過濾器
try { throw new WebException("Request timed out..", WebExceptionStatus.Timeout); } catch (WebException webEx) when (webEx.Status == WebExceptionStatus.Timeout) { // Exception handling }
- 在Catch使用Await
old: bool hasError = false; string errorMessage = null; try { //etc. } catch (MyException ex) { hasError = true; errorMessage = ex.Message; } if (hasError) { await new MessageDialog().ShowAsync(errorMessage); } new: try { //etc. } catch (MyException ex) { await new MessageDialog().ShowAsync(ex.Message); }
文章來源地址http://www.zghlxwxcb.cn/news/detail-465851.html
文章來源:http://www.zghlxwxcb.cn/news/detail-465851.html
到了這里,關于C# 6.0 語法新特性的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!