簡短介紹 C# 6 的新特性
幾周前我在不同的地方讀到了有關C#6的一些新特性。我就決定把它們都收集到一起,如果你還沒有讀過,就可以一次性把它們都過一遍。它們中的一些可能不會如預期那樣神奇,但那也只是目前的更新。
你可以通過下載VS2014或者安裝這里針對visual studio2013的Roslyn包來獲取它們。
那么讓我們看看吧:
1. $標識符
$的作用是簡化字符串索引。它與C#中那些內部使用正則表達式匹配實現索引的動態特性不同。示例如下:
var col = new Dictionary<string, string>() { $first = "Hassan" };//Assign value to member //the old way: col.$first = "Hassan";
//the new way: col["first"] = "Hassan";</pre>
2. 異常過濾器
VB編譯器中早已支持異常過濾器,現在C#也支持了。異常過濾器可以讓開發人員針對某一條件創建一個catch塊。只有當條件滿足時catch塊中的代碼才會執行,這是我最喜歡的特性之一,示例如下:
try { throw new Exception("Me"); } catch (Exception ex) if (ex.Message == "You")3. catch和finally塊中await關鍵字
據我所知,沒有人知道C# 5中catch和finally代碼塊內await關鍵字不可用的原因,無論何種寫法它都是不可用的。這點很好因為開發人員經常想查看I/O操作日志,為了將捕捉到的異常信息記錄到日志中,此時需要異步進行。
try { DoSomething(); } catch (Exception) { await LogService.LogAsync(ex); }4. 聲明表達式
這個特性允許開發人員在表達式中定義一個變量。這點很簡單但很實用。過去我用asp.net做了許多的網站,下面是我常用的代碼:
long id; if (!long.TryParse(Request.QureyString["Id"], out id)) { }優化后的代碼:
if (!long.TryParse(Request.QureyString["Id"], out long id)) { }這種聲明方式中變量的作用域和C#使用一般方式聲明變量的作用域是一樣的。
5. Static的使用
這一特性允許你在一個using語句中指定一個特定的類型,此后這個類型的所有靜態成員都能在后面的子句中使用了.
using System.Console;namespace ConsoleApplication10 { class Program { static void Main(string[] args) { //Use writeLine method of Console class //Without specifying the class name WriteLine("Hellow World"); } } }</pre>
6. 屬性的自動初始化:
C# 6 自動舒適化屬性就像是在聲明位置的域。這里唯一需要知道的是這個初始化不會導致setter方法不會在內部被調用. 后臺的域值是直接被設置的,下面是示例:
public class Person { // You can use this feature on both //getter only and setter / getter only propertiespublic string FirstName { get; set; } = "Hassan"; public string LastName { get; } = "Hashemi"; }</pre>
7. Primary Constructor:
Woohooo, primary constructors will help destroy the pain of capturing values of constructor parameters to fields in the class for further operations. This is really useful. The main purpose for it is using constructor parameters for initialization. When declaring a primary constructor all other constructors must call the primary constructor using :this().
here is an example finally:
//this is the primary constructor: class Person(string firstName, string lastName) { public string FirstName { get; set; } = firstName; public string LastName { get; } = lastName; }notice that declaration of primary constructor is at the top of the class.
本文地址:http://www.oschina.net/translate/briefly-exploring-csharp-new-features
原文地址:http://www.codeproject.com/Articles/808732/Briefly-exploring-Csharp-new-features
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!