歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C# 6.0 的新特性

C# 6.0 的新特性

日期:2017/3/1 9:31:22   编辑:Linux編程

本文的內容包括引入C#6.0中的新的語言特性有哪些. 還有已經被引入的代碼名稱為 “Roslyn”新編譯器. 編譯器是開放源碼的,並且可以從 codeplex 網站的這個地址下載到源代碼: https://roslyn.codeplex.com/.

C# 6.0 中的新特性

我們可以對這些新特性一個一個的進行討論,而首先要列出 C# 6.0 中這些特性的一個清單

  1. 自動的屬性初始化器 Auto Property Initializer
  2. 主構造器 Primary Consturctor
  3. 字典初始化器 Dictionary Initializer
  4. 聲明表達式 Declaration Expression
  5. 靜態的Using Static Using
  6. catch 塊中的 await
  7. 異常過濾器 Exception Filter
  8. 用於檢查NULL值的條件訪問操作符

1. 自動的屬性初始化器Auto Property initialzier

之前的方式

初始化一個自動屬性Auto Property的唯一方式,就是去實現一個明確的構造器,在裡面對屬性值進行設置.

public class AutoPropertyBeforeCsharp6
{
private string _postTitle = string.Empty;
public AutoPropertyBeforeCsharp6()
{
//assign initial values
PostID = 1;
PostName = "Post 1";
}

public long PostID { get; set; }

public string PostName { get; set; }

public string PostTitle
{
get { return _postTitle; }
protected set
{
_postTitle = value;
}
}
}

有了這個特性之後的方式

使用 C# 6 自動實現的帶有初始值的屬性可以不用編寫構造器就能被初始化. 我們可以用下面的代碼簡化上面的示例:

public class AutoPropertyInCsharp6
{
public long PostID { get; } = 1;

public string PostName { get; } = "Post 1";

public string PostTitle { get; protected set; } = string.Empty;
}

2. 主構造器

我們使用構造器主要是來初始化裡面的值.(接受參數值並將這些參數值賦值給實體屬性).

之前的方式

public class PrimaryConstructorsBeforeCSharp6
{
public PrimaryConstructorsBeforeCSharp6(long postId, string postName, string postTitle)
{
PostID = postId;
PostName = postName;
PostTitle = postTitle;
}

public long PostID { get; set; }
public string PostName { get; set; }
public string PostTitle { get; set; }
}

有了這個特性之後的方式

public class PrimaryConstructorsInCSharp6(long postId, string postName, string postTitle)
{
public long PostID { get; } = postId;
public string PostName { get; } = postName;
public string PostTitle { get; } = postTitle;
}

在 C# 6 中, 主構造器為我們提供了使用參數定義構造器的一個簡短語法. 每個類只可以有一個主構造器.

如果你觀察上面的示例,會發現我們將參數初始化移動到了類名的旁邊.

你可能會得到下面這樣的錯誤“Feature ‘primary constructor’ is only available in ‘experimental’ language version.”(主構造器特性只在實驗性質的語言版本中可用), 為了解決這個問題,我們需要編輯 SolutionName.csproj 文件,來規避這個錯誤 . 你所要做的就是在 WarningTag 後面添加額外的設置

<LangVersion>experimental</LangVersion>

Feature 'primary constructor' is only available in 'experimental' language version

‘主構造器’只在‘實驗’性質的語言版本中可用

3. 字典初始化器

之前的方式

編寫一個字典初始化器的老辦法如下

public class DictionaryInitializerBeforeCSharp6
{
public Dictionary<string, string> _users = new Dictionary<string, string>()
{
{"users", "Venkat Baggu Blog" },
{"Features", "Whats new in C# 6" }
};
}

有了這個特性之後的方式

我們可以像數組裡使用方括號的方式那樣定義一個字典初始化器

public class DictionaryInitializerInCSharp6
{
public Dictionary<string, string> _users { get; } = new Dictionary<string, string>()
{
["users"] = "Venkat Baggu Blog",
["Features"] = "Whats new in C# 6"
};
}

4. 聲明表達式

之前的方式

public class DeclarationExpressionsBeforeCShapr6()
{
public static int CheckUserExist(string userId)
{
//Example 1
int id;
if (!int.TryParse(userId, out id))
{
return id;
}
return id;
}

public static string GetUserRole(long userId)
{
////Example 2
var user = _userRepository.Users.FindById(x => x.UserID == userId);
if (user!=null)
{
// work with address ...

return user.City;
}
}
}

有了這個特性之後的方式

在 C# 6 中你可以在表達式的中間聲明一個本地變量. 使用聲明表達式我們還可以在if表達式和各種循環表達式中聲明變量

public class DeclarationExpressionsInCShapr6()
{
public static int CheckUserExist(string userId)
{
if (!int.TryParse(userId, out var id))
{
return id;
}
return 0;
}

public static string GetUserRole(long userId)
{
////Example 2
if ((var user = _userRepository.Users.FindById(x => x.UserID == userId) != null)
{
// work with address ...

return user.City;
}
}
}

5. 靜態的 Using

之前的方式

對於你的靜態成員而言,沒必要為了調用一個方法而去弄一個對象實例. 你會使用下面的語法

TypeName.MethodName

public class StaticUsingBeforeCSharp6
{
public void TestMethod()
{
Console.WriteLine("Static Using Before C# 6");
}
}

之後的方式

在 C# 6 中,你不用類名就能使用 靜態成員 . 你可以在命名空間中引入靜態類.

如果你看了下面這個實例,就會看到我們將靜態的Console類移動到了命名空間中

using System.Console;
namespace newfeatureincsharp6
{
public class StaticUsingInCSharp6
{
public void TestMethod()
{
WriteLine("Static Using Before C# 6");
}
}
}

6. catch塊裡面的await

C# 6 之前catch和finally塊中是不能用 await 關鍵詞的. 在 C# 6 中,我們終於可以再這兩個地方使用await了.

try
{
//Do something
}
catch (Exception)
{
await Logger.Error("exception logging")
}

7. 異常過濾器

異常過濾器可以讓你在catch塊執行之前先進行一個 if 條件判斷.

看看這個發生了一個異常的示例,現在我們想要先判斷裡面的Exception是否為null,然後再執行catch塊

//示例 1
try
{
//Some code
}
catch (Exception ex) if (ex.InnerException == null)
{
//Do work

}

//Before C# 6 we write the above code as follows

//示例 1
try
{
//Some code
}
catch (Exception ex)
{
if(ex.InnerException != null)
{
//Do work;
}
}

8. 用於檢查NULL值的條件訪問操作符?.

看看這個實例,我們基於UserID是否不為null這個條件判斷來提取一個UserRanking.

之前的方式

var userRank = "No Rank";
if(UserID != null)
{
userRank = Rank;
}

//or

var userRank = UserID != null ? Rank : "No Rank"

有了這個特性之後方式

var userRank = UserID?.Rank ?? "No Rank";

C# 6.0中的新特性 第一次出現在 Venkat Baggu 博客 上。

C#多線程編程實例 線程與窗體交互【附源碼】 http://www.linuxidc.com/Linux/2014-07/104294.htm

C#數學運算表達式解釋器 http://www.linuxidc.com/Linux/2014-07/104289.htm

在C語言中解析JSON配置文件 http://www.linuxidc.com/Linux/2014-05/101822.htm

C++ Primer Plus 第6版 中文版 清晰有書簽PDF+源代碼 http://www.linuxidc.com/Linux/2014-05/101227.htm

Copyright © Linux教程網 All Rights Reserved