日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C# 6 的新特性

發布時間:2025/3/11 C# 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C# 6 的新特性 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

還是記錄一下吧,好記性不如爛筆頭。

1、靜態的 using 聲明

靜態的 using 聲明允許條用方法時候不適用類名。

C# 5:

using System; //etc Console.WriteLine("Hello,World!");

C# 6:

using static System.Console; //etc. Writeline("Hello,World");

2、表達式體方法

表達式體方法只包括一個可以用 lambda語法編寫語句:

C# 5:

public bool IsSquare(Rectangle rect) {return rect.Height == rect.Width; }

C# 6:

public bool IsSquare (Rectangle rect) => rect.Height == rect.Width;

3、表達式體屬性?

與表達式體方法類似,只有get存取器的單行屬性可以用lambda語法編寫:

C# 5

public string FullName {get{return FirstName + "" + LastName;} }

C# 6

public string FullName => FirstName + "" +LastName;

4、自動實現的屬性初始化器

自動實現的屬性可以用屬性初始化器來初始化:

C# 5

public class Person {public Person(){Age = 24;}public int Age { get;set;} }

? ? ? ? ? C# 6

public class Person {public int Age {get;set;} = 42; }

5、只讀的自動屬性

?為了實現只讀屬性,C# 5 需要使用完整的屬性語法:而在C# 6中,可以使用自動實現的屬性:

C# 5

private readonly int _bookId;public BooKId {get{ret _bookId;} }

?C# 6

public BookId {get;}

6、nameof 運算符

使用新的nameof運算符,可以訪問字段名、屬性名、方法名或者類型名。這樣,在重構時,就不會遺漏名稱的改變:

C# 5

public void Method( object o ) {if( o == null) throw new ArgumentNullException("o"); }

?C# 6

public void Method (object o) {if(o == null) throw new ArgumentNullException (nameof(0)); }

7、?空值傳播運算符

空值傳播運算符簡化了空值的檢查:

C#? 5

int? age = p == null ? null : p.Age;

?C# 6

int? age = p?.Age;

? ? ? ? ? ?新語法也有觸發事件的優點:

? ? ? ? ? ?C# 5

var handler = Event; if(handler != null) {handler(source,e); }

C# 6

handler?.Invoke(source,e);

8、字符串插值

字符串插值刪除了對 string.Format的調用,它不在字符串中使用編號的格式占位符,占位符可以包含表達式:

C# 5

public override ToString() {return string.Format("{0},{1}",Title,Publisher); }

?C#? 6

public override ToString() => $"{Title} {Publisher}";

9、字典初始化器

字典現在可以用字典初始化器來初始化,類似于集合初始化器。

C#? 5

var dict = new Dictionary<int , string>(); dict.Add(3,"three"); dict.Add(7,"seven");

? ? ? ? ? C# 6

var dict = new Dictionary <int ,string>() {[3] = "three",[7] = "seven" }

10、異常過濾器

異常過濾器允許在捕獲異常之前過濾他們。

C# 5

try {//etc. } catch (MyException ex) {if(ex.ErrorCode != 405) throw; }

? ? ? ? ? ?C# 6

try {//etc. } catch (MyExctption ex) when (ex.ErrorCode == 405) {//etc. }

新語法的優勢是,它不僅減少了代碼額的長度,而且沒有改變堆棧跟蹤 -------在 C# 5 中會改變堆棧跟蹤。


11、Catch 中的 await

await 現在可以在catch子句中使用。C# 5需要一種變通方法:

C# 5

bool hasError = false; string errorMessage = null; try {//etc. } catch (MyException ex) {hasError = true;errorMessage = ex.Message; } if(hasError) {await new MessageDialog().ShowAsync(errorMessage); }

? ? ? ? ? ?C#? 6

try {//etc. } catch (MyException ex) {await new MessageDialog().ShowAsync(ex.Message); }

?

?

?

?

?

?

?

?

?

總結

以上是生活随笔為你收集整理的C# 6 的新特性的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。