1. 程式人生 > >VS2015使用C#6.0中的那些新特性

VS2015使用C#6.0中的那些新特性

1、自動屬性的增強

1.1、自動屬性初始化 (Initializers for auto-properties)

C#4.0下的果斷實現不了的。
這裡寫圖片描述

這裡寫圖片描述
只要接觸過C#的肯定都會喜歡這種方式。真是簡潔方便呀。

1.2、只讀屬性初始化Getter-only auto-properties

先來看一下我們之前使用的方式吧

public class Customer
{
    public string Name { get; }

    public Customer(string firstName,string lastName)
    {
        Name = firstName +" "
+ lastName; } }

再來看一下C#6.0中

public class Customer
    {
        public string FirstName { get; }="aehyok";
        public string LastName { get; }="Kris";

    }

和第一條自動屬性初始化使用方式一致。

2、Expression bodied function members

2.1 用Lambda作為函式體Expression bodies on method-like members

public Point Move
(int dx, int dy) => new Point(x + dx, y + dy);

再來舉一個簡單的例子:一個沒有返回值的函式

public void Print() => Console.WriteLine(FirstName + " " + LastName);

2.2、Lambda表示式用作屬性Expression bodies on property-like function members

public override string ToString()
        {
            return FirstName + " "
+ LastName; }

現在C#6中

public class User
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public override string ToString() => string.Format("{0}——{1}", FirstName, LastName);

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

3、引用靜態類Using Static

在Using中可以指定一個靜態類,然後可以在隨後的程式碼中直接使用靜態的成員
這裡寫圖片描述

4、空值判斷Null-conditional operators

直接來看程式碼和執行結果
這裡寫圖片描述
通過結果可以發現返回的都為null,再也不像以前那樣繁瑣的判斷null勒

5、字串嵌入值

在字串中嵌入值

之前一直使用的方式是
這裡寫圖片描述
現在我們可以簡單的通過如下的方式進行拼接
這裡寫圖片描述

6、nameof表示式nameof expressions

在方法引數檢查時,你可能經常看到這樣的程式碼(之前用的少,這次也算學到了)

public static void AddCustomer(Customer customer)
{
    if (customer == null)
    {
        throw new ArgumentNullException("customer");
    }
}

裡面有那個customer是我們手寫的字串,在給customer改名時,很容易把下面的那個字串忘掉,C#6.0 nameof幫我們解決了這個問題,看看新寫法

public static void AddCustomer(Customer customer)
{
    if (customer == null)
    {
        throw new ArgumentNullException(nameof(customer));
    }
}

7、帶索引的物件初始化器Index initializers

直接通過索引進行物件的初始化,原來真的可以實現
這裡寫圖片描述
通過這種方式可以發現字典中只有三個元素,所以也就只有這三個索引可以訪問額,其他型別的物件和集合也是可以通過這種方式進行初始化的,在此就不進行一一列舉了。

8、異常過濾器 (Exception filters)

先來看一個移植過來的方法

try
{
    var numbers = new Dictionary<int, string> {[7] = "seven",[9] = "nine",[13] = "thirteen" };
}
catch (ArgumentNullException e)
{
    if (e.ParamName == "customer")
    {
        Console.WriteLine("customer can not be null");
    }
}

在微軟的文件中還給出了另一種用法,這個異常會在日誌記錄失敗時拋給上一層呼叫者

private static bool Log(Exception e)
{
    ///處理一些日誌
    return false;
} 

static void Main(string[] args)
{

    try
    {
        ///
    }
    catch (Exception e){if (!Log(e))
        {

        }
    }

    Console.ReadLine();
}

9、catch和finally 中的 await —— Await in catch and finally blocks

在C#5.0中,await關鍵字是不能出現在catch和finnaly塊中的。而在6.0中

try
{
    res = await Resource.OpenAsync(…); // You could do this. … 
}
catch (ResourceException e)
{
    await Resource.LogAsync(res, e); // Now you can do this … 
} finally
{
    if (res != null)
        await res.CloseAsync(); // … and this. 
}

10、無引數的結構體建構函式—— Parameterless constructors in structs

這裡寫圖片描述

C# 6.0 新特性彙總

1. 靜態using(static using)

靜態using宣告允許不使用類名直接呼叫靜態方法

//The static using declaration allows invoking static methods without the class name.
//In C# 5
using System;
Console.WriteLine("Hello, World!");
//In C# 6
using static System.Console;
WriteLine("Hello, World");

2. 表示式方法(Expression-Bodied Methods)

使用表示式方法,只有一條語句的方法可以使用lambda語法寫。

//With expression-bodied methods, a method that includes just one statement can be written with the lambda syntax.
//In C# 5
public bool IsSquare(Rectangle rect)
{
return rect.Height == rect.Width;
}
//In C# 6
public bool IsSquare(Rectangle rect) => rect.Height == rect.Width;

3. 表示式屬性(Expression-Bodied Properties)

跟表示式方法類似,只有一個get訪問器的單行屬性可以使用lambda語法寫。

//Similar to expression-bodied methods, one-line properties with only a get accessor can be written with the lambda syntax
//In C# 5
public string FullName
{
get
{
return FirstName +"" + LastName;
}
}
//In C# 6
public string FullName => FirstName +"" + LastName;

4. 自動屬性初始化器(Auto-Implemented Property Intializers)

自動屬性可以使用屬性初始化器初始化。

//Auto-implemented properties can be initialized with a property initializer.

//In C# 5
public class Person
{
public Person()
{
Age = 24;
}
public int Age {get; set;}
}
//In C# 6
public class Person
{
public int Age {get; set;} = 42;
}

5. 只讀自動屬性(Read-Only Auto Properties)

C# 5需要完整的屬性語法實現只讀屬性,C# 6可以使用自動屬性實現。

//To implement read-only properties, C# 5 requires the full property syntax. With C# 6, you can do this using auto-implemented properties.
//In C# 5
private readonly int _bookId;
public BookId
{
get
{
return _bookId;
}
}
//In C# 6
public BookId {get;}

6. nameof操作符(nameof Operator)

欄位、屬性、方法和型別的name可以通過nameof訪問。使用nameof,可以方便的重構name變化。

//With the new nameof operator, names of fields, properties, methods, or types can be accessed. With this, name changes are not missed with refactoring.

//In C# 5
public void Method(object o)
{
if (o == null) throw new ArgumentNullException("o");
//In C# 6
public void Method(object o)
{
if (o == null) throw new ArgumentNullException(nameof(o));

7. Null傳遞操作符(Null Propagation Operator)

Null傳遞操作符簡化了空值檢查。

//The null propagation operator simplifies null checks.
//In C# 5
int? age = p == null ? null : p.Age;
var handler = Event;
if (handler != null)
{
handler(source, e);
}
//In C# 6
int? age = p?.Age;
handler?.Invoke(source, e);

8. 字串插值(String Interpolation)

字串差值移除了對string.Format的呼叫,使用表示式佔位符取代數字格式佔位符。

//The string interpolation removes calls to string.Format. Instead of using numbered format placeholders in the string, the placeholders can include expressions.
//In C# 5
public override ToString()
{
return string.Format("{0}, {1}", Title, Publisher);
}
//In C# 6
public override ToString() => $"{Title} {Publisher}";

9. 字典初始化器(Dictionary Initializers)

字典可以使用類似集合的字典初始化器初始化。

//Dictionaries can now be initialized with a dictionary initializer—similar to the collection initializer.
//In C# 5
var dict = new Dictionary<int, string>();
dict.Add(3,"three");
dict.Add(7,"seven");
//In C# 6
var dict = new Dictionary<int, string>()
{
[3] ="three",
[7] ="seven"
};

10. 異常過濾器(Exception Filters)

異常過濾器允許你在捕獲異常前進行過濾。

//Exception filters allow you to filter exceptions before catching them.
//In C# 5
try
{
//etc.
} catch (MyException ex)
{
if (ex.ErrorCode != 405) throw;
// etc.
}
//In C# 6
try
{
//etc.
} catch (MyException ex) when (ex.ErrorCode == 405)
{
// etc.
}

11. 在Catch使用Await(Await in Catch)

await可以在catch塊中直接使用,C# 5中需要變通使用。

//await can now be used in the catch clause. C# 5 required a workaround.
//In 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);
}
//In C# 6
try
{
//etc.
} catch (MyException ex)
{
await new MessageDialog().ShowAsync(ex.Message);
}

相關推薦

React 16.0特性——portal及其注意點

簡要介紹:React16.0中釋出了很多新特性,我們來看portal,React提供了一個頂級API—portal,用來將子節點渲染到父節點之外的dom節點 1.基本用法 (1)在React15.X版本中,我們只能講子節點在父節點中渲染,基本用法如下:

(資料科學學習手札73)盤點pandas 1.0.0特性

本文對應指令碼及資料已上傳至我的Github倉庫https://github.com/CNFeffery/DataScienceStudyNotes 1 簡介   毫無疑問pandas已經成為基於Python的資料分析領域最重要的包,而就在最近,pandas終於迎來了1.0.0版本,對於pandas來說這

VS2015使用C#6.0那些特性

1、自動屬性的增強 1.1、自動屬性初始化 (Initializers for auto-properties) C#4.0下的果斷實現不了的。 只要接觸過C#的肯定都會喜歡這種方式。真是簡潔方便呀。 1.2、只讀屬性初始化Getter-

VS2015 C#6.0 那些特性

前言       VS2015在自己機器上確實是裝好了,費了老勁了,想來體驗一下跨平臺的快感,結果被微軟狠狠的來了一棒子了,裝好了還是沒什麼用,應該還需要裝Xarmain外掛,配置一些引數吧,由於這塊之前從未接觸過,想了想還是先不把時間繼續浪費在這裡了,於是乎來體驗一下新特性了。 1、自動屬性的增

Android6.0系統添加那些特性

文本 第一次 分辨 提升 暴露 per 樣式 一段時間 windows ??? 北京時間9月30日淩晨在美國舊金山舉行2015年秋季新品公布會。在公布會上代號為“M

Android 6.0 技術

七、低功耗藍芽掃描優化   優化了低功耗藍芽掃描優化的掃描。現在低功耗藍芽的應用越來越多,很多 APP 都需要掃描裝置,掃描裝置是一個非常重的操作,希望這次改動,能夠帶來一些改善。   八、支援主題化的 ColorStateLists   使用

0.6.Java 8 . 7 特性

Java 7 1.1. Switch語句支援string型別 1.2. 泛型例項的建立可以通過型別推斷來簡化 可以去掉後面new部分的泛型型別,只用<>就可以了。 //使用泛型前 List strList = new ArrayList(); List<

PHP 5.3、5.4、5.5、5.6 特性

PHP 5.6 1、可以使用表示式定義常量 https://php.net/manual/zh/migration56.new-features.php 在之前的 PHP 版本中,必須使用靜態值來定義常量,宣告屬性以及指定函式引數預設值。 現在你可以使用包括數值、字串字面量以及其他常量在

Java 5/Java 6/Java7/Java 8特性收集

lan 鏈接 develop new strong tar chrom eve ref 前言: Java 8對應的JDK版本為JDK8,而官網下載回來安裝的時候,文件夾上寫的是JDK1.8,同一個意思。(而這個版本命名也是有規律的,以此類推) 一、Java 5 1、h

vs2015和VC++6.0while (scanf("%d", &x) != EOF)輸入如何結束

.cn 完數 .com 輸入 如何 blog www vc++ -a vs2015和VC++6.0中while (scanf("%d", &x) != EOF)輸入如何結束 VS2015中:    解決方案:輸完數據->回車->ctrl+z->回車

Unity 4.0 動畫系統——MecAnim

alt clas 講解 unit 組件 之一 new src align   分享一個文檔資料,關於動畫系統的,版本應該很老了,但是有借鑒意義的;     Unity 4.0 已於 2012 年 11 月 15 日正式發布,Unity 每一次版本的提升,都給遊戲開發者帶來

技術大牛論道HBase 3.0 可能的特性

去除 進一步 調整 還需 備份和恢復 blog 部署 filter 技術分享 摘要: 經過了四年的發展歷程,HBase 2.0終於發布上線,其增加了很多的新特性,能夠更好地適應更多的場景,但是也有一些原本計劃的特性並沒有隨之上線。在未來的HBase 3.0版本中,又有哪些特

Spring Framework 5 特性

jpg 幹凈 map 避免 strong findbugs ora htm 習慣 Spring Framework 5 中的新特性 Spring 5 如何利用 Java 8 的函數式語法和一種新的反應式編程模型 Alex Theedom2017 年 10 月 18 日

MySQL8.0 · 優化器特性 · Cost Model, 直方圖及優化器開銷優化

成了 select ams 增加 表數據 未來 data 數量 建立索引 摘要: MySQL當前已經發布到MySQL8.0版本,在新的版本中,可以看到MySQL之前被人詬病的優化器部分做了很多的改動,由於筆者之前的工作環境是5.6,最近切換到最新的8.0版本,本文涵蓋了一些

VC 6 0新增庫檔案和標頭檔案

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

Java 8 特性Streams

Stream 作為 Java 8 的一大亮點,它與 java.io 包裡的 InputStream 和 OutputStream 是完全不同的概念。 使用 Stream API 無需編寫一行多執行緒的程式碼,就可以很方便地寫出高效能的併發程式。所以說,Java 8 中首次出現的 java.util.

c++ builder 6.0 使用大漠外掛

以前用VC寫的指令碼控制程式,可以使用bcb6.0來寫了。這裡寫個備註,在bcb6.0中的使用方法     step1.註冊dm.dll  {不然提示沒有註冊類} Regsvr32 dm.dll step2.匯入型別庫

【轉載】Django 2.0版本的特性

2017年12月2日,Django官方釋出了2.0版本,成為多年來的第一次大版本提升,那麼2.0對廣大Django使用者有哪些變化和需要注意的地方呢? 一、Python相容性 Django 2.0支援Python3.4、3.5和3.6。Django官方強烈推薦每個系

Vue高版本一些特性的使用詳解

一、深度作用選擇器( >>> ) 嚴格來說,這個應該是vue-loader的功能。”vue-loader”: “^12.2.0” 在專案開發中,如果業務比較複雜,特別像中臺或B端功能頁面都不可避免的會用到第三方元件庫,產品有時會想對這些元件進行一些UI方面的定

Vue高版本一些特性的使用

主要包括以下幾點: 深度作用選擇器( >>> ) 我在另一篇文章中也有提到這點Vue: scoped 樣式與 CSS Module 對比 元件配置項inheritAttrs、元件例項屬性$attrs和$listeners 發生在父子元件之間