程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 探秘C# 6.0 的新特征

探秘C# 6.0 的新特征

編輯:C#入門知識

探秘C# 6.0 的新特征。本站提示廣大學習愛好者:(探秘C# 6.0 的新特征)文章只能為提供參考,不一定能成為您想要的結果。以下是探秘C# 6.0 的新特征正文


C# 6.0 中的新特征

我們可以對這些新特征一個一個的停止評論辯論,而起首要列出 C# 6.0 中這些特征的一個清單

主動的屬性初始化器 Auto Property Initializer

主結構器 Primary Consturctor

字典初始化器 Dictionary Initializer

聲明表達式 Declaration Expression

靜態的Using Static Using

catch 塊中的 await

異常過濾器 Exception Filter

用於檢討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>

‘主結構器'只在‘試驗'性質的說話版本中可用

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";

 以上所述就是本文的全體內容了,願望年夜家可以或許愛好。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved