[C#.NET] C# 6.0 新功能

  • 8871
  • 0
  • C#
  • 2016-12-05

[C#.NET] C# 6.0 新功能

C# 6.0 這次不像以往有增加大功能,僅是新增新的語法,讓程式碼看起來更簡潔,你可以選擇不用它,但要看的懂

本文連結:

#例外過濾和非同步:

#自動屬性初始化:

#字典集合初始化:

#Expression-bodied function members:

#using 靜態命名類別:

#null 條件判斷:

#nameof取得變數名稱:

 

例外過濾和非同步:

增加 when 語句來決定是否進入 catch 區段;如下範例,當例外訊息包含了 test 字串才在畫面上,否則拋出例外:

private void RunFlow()
{
	try
	{
		Class1 c1 = new Class1();
		c1.GetValue();
	}
	catch (Exception ex) when (ex.Message.Contains("test"))
	{
		Console.WriteLine("捕獲到錯誤");
	}
	catch (Exception ex)
	{
		throw;
	}

}

 

再來,catch 跟 finally 區段也能用 await 了,如下範例:

private static async void RunFlow()
{
	try
	{
		var c1 = new Class1();
		c1.GetValue();
	}
	catch (Exception ex) when (ex.Message.Contains("test"))
	{
		Console.WriteLine("捕獲到錯誤");
		await Task.Delay(500);
	}
	catch (Exception ex)
	{
		throw;
	}
	finally
	{
		await Task.Delay(500);
	}
}

String Interpolatin:

以往我動態兜字串時都會用 string.Format,而不用 "+" 來連接字串,原因是 string.Format,語意上比 "+" 更簡潔,也更好維護,現在多了 string interpolatin,在原本的 string.Format 哪一行

舊的寫法

string name = string.Format("FullName:{0},{1}", m.FirstName, m.LastName);

 

新的寫法,$"{變數}"

string name = $"FullName:{m.FirstName} , {m.LastName}";

 

當然也可以用 ? :

var s = $"{p.Name} is {p.Age} year{(p.Age == 1 ? "" : "s")} old";

 

新寫法看起來更簡潔了

 

自動屬性初始化:

以往自動屬性初始化無法直接指定,必須要寫在建構函式,現在可以直接指定狀態

public string Name { get; set; } = "余小章";

 

唯讀屬性初始化

public string Name { get; } = "余小章";

 

字典集合初始化:

以前寫法

var members = new Dictionary<int, Member>
{
	{111, new Member {FirstName = "Sachin", LastName = "Karnik"}},
	{112, new Member {FirstName = "Dina", LastName = "Salimzianova"}},
	{113, new Member {FirstName = "Andy", LastName = "Ruth"}}
};
var numbers = new Dictionary<int, string>
{
	{111, "Karnik"}, {112, "Salimzianova"}, {113, "Ruth"}
};

 

現在這樣寫,雖然看起來改變不太大

var members1 = new Dictionary<int, Member>
{
	[111] = new Member {FirstName = "Sachin", LastName = "Karnik"},
	[112] = new Member {FirstName = "Dina", LastName = "Salimzianova"},
	[113] = new Member {FirstName = "Andy", LastName = "Ruth"}
};
var numbers1 = new Dictionary<int, string>
{
	[111] = "Karnik", [112] = "Salimzianova", [113] = "Ruth"
};

 

Expression-bodied function members:

當方法內容只有一行的時候,可以用 lambda 縮成一行,剛試了一下,索引子、方法、欄位可以這樣寫,自動屬性不行

方法:

internal class Member
{
	public string FirstName { get; set; }
	public string LastName { get; set; }

	public override string ToString()
	{
		return $"first:{FirstName},{LastName}";
	}
}

可以用 lambda 縮成以下,看起來就像是具名方法裡面又包了匿名方法,

public override string ToString() => $"first:{this.FirstName},{this.LastName}";

欄位:

public string FullName => $"first:{this.FirstName},{this.LastName}";

 

索引子:

internal class MemberCollection
{
	private static readonly List<Member> s_members;

	static MemberCollection()
	{
		if (s_members == null) s_members = new List<Member> {new Member()};
	}

	public Member this[int id] => s_members[id];
}

 

using 靜態命名類別:

以前的寫法:

using System;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Member m = new Member {FirstName = "余", LastName = "小章"};
            string name = $"FullName:{m.FirstName},{m.LastName}";
            Console.WriteLine(name);
            Console.ReadLine();
        }
    }
}

 

using System;
using static System.Console;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Member m = new Member {FirstName = "余", LastName = "小章"};
            string name = $"FullName:{m.FirstName},{m.LastName}";
            WriteLine(name);
            ReadLine();
        }
    }
}

 

null 條件判斷:

原本我會這樣寫

private static int? GetFirstNameLength(Member member)
{
	int? result = null;
	if ((member == null) || (member.FirstName == null)) return null;
	result = member.FirstName.Length;
	return result;
}

 

現在可以用問號取代 == null,判斷 null 的部分就變很短了

private static int? GetFirstNameLength(Member member)
{
    int? result = null;
    result = member?.FirstName?.Length;
    return result;
}

 

nameof取得變數名稱:

原本取得變數名稱,要用手敲

private static int? GetFirstNameLength(Member member)
{
	if (member==null)
	{
		throw new ArgumentNullException("member");
	}
}

 

現在透過nameof就可以直接取得

private static int? GetFirstNameLength(Member member)
{
	if (member==null)
	{
		throw new ArgumentNullException(nameof(member));
	}
}

結論:

我最喜歡的功能是 null 條件判斷 還有 exception filter

本文出自:http://www.dotblogs.com.tw/yc421206/archive/2015/09/18/153377.aspx

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo